给UIButton设置背景颜色
.h文件
#import <UIKit/UIKit.h>
@interface UIButton (FillColor)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;
@property (nonatomic, strong) NSString * titleName;
.m文件
#import "UIButton+FillColor.h"
#import "objc/runtime.h"
static const void * titleNameBy = &titleNameBy;
@implementation UIButton (FillColor)
@dynamic titleName;
// 添加自定义属性
-(void)setTitleName:(NSString *)titleName {
objc_setAssociatedObject(self, titleNameBy, titleName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)titleName {
return objc_getAssociatedObject(self, titleNameBy);
}
// 设置背景颜色for state
- (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
使用方法:
[button setBackgroundColor:[UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1.0] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];
参考文章:
给UIButton设置BackgroundColor:forState
iOS小技巧 - 为按钮设置不同状态下的背景色