UIButton重写 - 图片和文字的位置

自己做项目时感觉用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];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容