创建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的颜色设置里填上,会自动显示。
网友评论