1.设置背景的两种方式
自定义按钮
#import "ZGKMeServiceBtn.h"
@implementation ZGKMeServiceBtn
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
// 在这里设置没有效果,因为init后才赋值label.text的值,所以textColor要在赋值text以后设置才有用,所以选择在layoutSubviews设置textColor的属性
// self.titleLabel.font = [UIFont systemFontOfSize:25];
// self.backgroundColor = ZGKColor(80, 157, 68, 1);
// self.layer.cornerRadius = 10;
// // textColor要设置在font之后才能生效
// self.titleLabel.textColor = [UIColor redColor];
}
return self;
}
- (void)layoutSubviews{
[super layoutSubviews];
self.titleLabel.font = [UIFont systemFontOfSize:25];
self.backgroundColor = ZGKColor(80, 157, 68, 1);
self.layer.cornerRadius = 10;
// textColor要设置在font之后才能生效
self.titleLabel.textColor = [UIColor redColor];
}
ZGKMeServiceBtn *serviceBtn = [[ZGKMeServiceBtn alloc] initWithFrame:CGRectMake(serviceBtnX, serviceBtnY, serviceBtnW, serviceBtnH)];
// 设置title以后再设置TitleColor
[serviceBtn setTitle:@"人工服务" forState:UIControlStateNormal];
// 设置文字颜色要指定状态
[serviceBtn setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
[serviceBtn addTarget:self action:@selector(serviceClick) forControlEvents:UIControlEventTouchUpInside];
综上,设置button的背景颜色有两种,一种是在自定义button的内部layoutSubvious方法中设置textColor的属性,但是要注意,设置textColor要在设置font属性之后赋值才有效。在外部button设置背景颜色的时候,要制定对应的状态,如:Normal, Highlight.