1.UIButton设置背景颜色的注意点

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.

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

推荐阅读更多精彩内容

  • 1 CALayer IOS SDK详解之CALayer(一) http://doc.okbase.net/Hell...
    Kevin_Junbaozi阅读 5,230评论 3 23
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,933评论 1 45
  • 尝试和大家一起探讨以下问题: view绘制渲染机制和runloop什么关系? 所谓的列表卡顿,到底是什么原因引发的...
    朽木自雕也阅读 3,085评论 4 9
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,032评论 3 119
  • 2018.7.14 星期六 晴 之前中亚旅行社搞活动,订了两张去临沂极地海洋世界的票,早上五点起床收拾一...
    chenjunhua108阅读 147评论 0 0