解决button被点击改变背景颜色的方法

2016-07-26  本文已影响1663人  EdwardSelf

创建UIButton的分类

.h文件:

- (void)setBackgroundColor:(UIColor*)backgroundColor forState:(UIControlState)state;

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

.m文件:

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

[selfsetBackgroundImage:[UIButtonimageWithColor:backgroundColor]forState:state];

}

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

CGRectrect =CGRectMake(0.0f,0.0f,1.0f,1.0f);

UIGraphicsBeginImageContext(rect.size);

CGContextRefcontext =UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, [colorCGColor]);

CGContextFillRect(context, rect);

UIImage*image =UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

returnimage;

}

宏定义:

#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]

用法:

[(UIButton *)sender setBackgroundColor:GetColorFromHex(0xD3D3D3) forState:UIControlStateNormal];

[(UIButton *)sender setBackgroundColor:GetColorFromHex(0xF76063) forState:UIControlStateHighlighted];

改变GetColorFromHex(),括号中的值,创建你想要的颜色,如果不知道,可以先滴出red,green,blue的数值,在storyboard的颜色设置里填上,会自动显示。

上一篇下一篇

猜你喜欢

热点阅读