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