iOS button背景颜色状态设置

来源:互联网 发布:知乎飞机杯 编辑:程序博客网 时间:2024/05/01 08:15

转自:http://blog.csdn.net/qq_20176153/article/details/52036422

关于button背景颜色(高亮状态)和(普通状态)

[self.confirmBtn setBackgroundImage:[Function imageWithColor:RGB(24415271)] forState:UIControlStateNormal];



封装类方法掉用:

//  颜色转换为背景图片

+ (UIImage *)imageWithColor:(UIColor *)color

{

    CGRect rect = CGRectMake(0.0f0.0f1.0f1.0f);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return image;

}










iOS小技巧 - 为按钮设置不同状态下的背景色
转自:http://www.2cto.com/kf/201412/361145.html
我们知道直接在Storyboard中设置按钮的背景色是不能根据不同状态来更改的,那问题来了,如果我们需要在不同的状态下(比如按钮没有被按下或者被按下),使得按钮呈现不同的背景色怎么办?
 
 
 
比如上图左边是按钮没有被按下时的背景色,右边是按钮被按下时的背景色。
 
第一种方案
我们知道按钮的Image属性可以在不同的状态下设置不同的图片,那最直观的办法就是提供两种背景色的图片,然后直接在Storyboard上通过设置不同状态下Image属性的值来达到目的。
 
但是这种方案最不好的地方就在于需要提供很多仅仅是颜色不同的图片,如果以后背景色改成其他色系怎么办?设置以后提供换肤功能,每一种皮肤都要提供一整套这些背景色图片吗?
 
第二种方案
我们还知道按钮的BackgroundImage也是可以根据不同状态来设置不同的背景图片的,那方案就来了,让程序根据颜色自动生成不同的纯色背景图片即可。
 
为了保证可复用性,定义一个UIButton的Category,实现如下:
 
@implementation UIButton (FillColor)
 
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
[self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}
 
+ (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;
}
 
@end
上述代码应该还是很直观的,调用的办法如下:
 
[self.button setBackgroundColor:GetColorFromHex(0xffff9000) forState:UIControlStateNormal];
[self.button setBackgroundColor:GetColorFromHex(0xffff6c00) forState:UIControlStateHighlighted];
其中GetColorFromHex是我自己定义的一个宏:
 
#define GetColorFromHex(hexColor) \
[UIColor colorWithRed:((hexColor >> 16) & 0xFF) / 255.0 \
green:((hexColor >>  8) & 0xFF) / 255.0 \
blue:((hexColor >>  0) & 0xFF) / 255.0 \
alpha:((hexColor >> 24) & 0xFF) / 255.0]
 
其实上述宏代码写成Category会更好,以后再做修改了。


0 0