UIButton在不同状态下显示不同背景色

本文介绍了一种在iOS开发中为UIButton设置不同状态下背景色的方法。通过创建纯色图片并将其应用于按钮的不同状态,实现按钮背景颜色的动态变化。

参考自:原文地址(内容与原文并无区别,只是自己以后方便使用整理了一下)

1.UIButton的background是不支持在针对不同的状态显示不同的颜色。

2.UIButton的backgroundImage是针对不同的状态的,所以思路就是在不同状态下的的时候,生成指定颜色的纯色图片。

 

关键代码:

/**

 *  设置不同状态下的背景色

 *

 *  @param backgroundColor 背景色

 *  @param state           状态

 */

- (void)setBackgroundColor:(UIColor *)backgroundColor State:(UIControlState)state{

        [self setBackgroundImage:[self imageWithColor:backgroundColor] forState:state];

}

 

/**

 *  生成纯色图片

 *

 *  @param color 颜色

 *

 *  @return 图片

 */

- (UIImage *)imageWithColor:(UIColor *)color{

    CGRect rect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);

    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;

}

 

GitHub地址:Locking-Xu_GitHub

转载于:https://www.cnblogs.com/small-octopus/p/4864338.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值