自己做项目时感觉用UIButton自己的图片和文字不太满意所有自己写了一个 ,有补充的多多交流。
.H
#import
@interface ZDYButton : UIButton
@property (nonatomic, assign) CGRect titleRect;//文字位置
@property (nonatomic, assign) CGRect imageRect;// 图片位置
@end
.M
#import "ZDYButton.h"
@implementation ZDYButton
// 重新写方法
- (CGRect)titleRectForContentRect:(CGRect)contentRect {
if (!CGRectIsEmpty(self.titleRect) && !CGRectEqualToRect(self.titleRect, CGRectZero)) {
return self.titleRect;
}
// 没有调用self.titleRect时,用默认的父类方法
return [super titleRectForContentRect:contentRect];
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect {
if (!CGRectIsEmpty(self.imageRect) && !CGRectEqualToRect(self.imageRect, CGRectZero)) {
return self.imageRect;
}
// 没有调用self.imageRect时,用默认的父类方法
return [super imageRectForContentRect:contentRect];
}
@end
ViewController.m
#import "ViewController.h"
#import "ZDYButton.h"
@interface ViewController ()
@property (nonatomic, strong) ZDYButton *butOne;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_butOne = [ZDYButton buttonWithType:UIButtonTypeCustom];
_butOne.backgroundColor = [UIColor greenColor];
[_butOne setTitle:@"按钮1" forState:UIControlStateNormal];
// 文字位置
_butOne.titleRect = CGRectMake(60, 10, 80, 50);
[_butOne setImage:[UIImage imageNamed:@"pick"] forState:UIControlStateNormal];
// 图片位置
_butOne.imageRect = CGRectMake(0, 10, 50, 50);
_butOne.frame = CGRectMake(50, 50, 150, 100);
_butOne.titleLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:_butOne];
}