UIButton设置高亮状态下的背景色

UIButton一般分为高亮的普通两种状态,原生的方法可以设置这两种不同状态下的文字颜色,文字内容,背景图片,按钮图片。但是不能设置按钮的背景色。在网上搜罗了一番,整理并总结了两个比较实用方法。

通过按钮的事件来设置背景色

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(50, 200, 100, 50)];
    [button1 setTitle:@"button1" forState:UIControlStateNormal];
    button1.backgroundColor = [UIColor orangeColor];
    [button1 addTarget:self action:@selector(button1BackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
    [button1 addTarget:self action:@selector(button1BackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
}
//  button1普通状态下的背景色
- (void)button1BackGroundNormal:(UIButton *)sender {
    sender.backgroundColor = [UIColor orangeColor];
}
//  button1高亮状态下的背景色
- (void)button1BackGroundHighlighted:(UIButton *)sender {
    sender.backgroundColor = [UIColor greenColor];
}

通过把颜色转换为UIImage来作为按钮不同状态下的背景图片

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(170, 200, 100, 50)];
    [button2 setTitle:@"button2" forState:UIControlStateNormal];
    [button2 setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
    [button2 setBackgroundImage:[self imageWithColor:[UIColor grayColor]] forState:UIControlStateHighlighted];
    [self.view addSubview:button2];
}
 
//  颜色转换为背景图片
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,276评论 4 61
  • 周五晚带着左姑娘见我的师弟,既是朋友的身份,也是媒人的角色,关于结果,我在等后续故事的发生,我很期待。 左姑娘是个...
    珊向一阅读 498评论 0 1
  • 正则表达式——古老而又强大的文本处理工具。仅用一段简短的表达式语句,就能快速地实现一个复杂的业务逻辑。掌握正则表达...
    古佛青灯度流年阅读 372评论 2 0
  • 第二章 家庭史 临床医师最重要的工具就是有效利用自我,人格和跟人相处方式,有效促进病人痊愈。 没人希望被粗鲁的对待...
    苏磊CHIVA阅读 531评论 0 0
  • 【二阶段 片段一】 片段选自高琳的职场实用指南《职得》,高琳是一个有20多年世界500强公司工作经验的一个女士。她...
    俊距离阅读 181评论 3 0