点击按钮改变状态的颜色

做项目经常遇到一个问题,给Button增加一个高亮状态,如果公司有ui还好,可以让ui给你切个高度状态的图片,没有ui只能自己切图或给按钮添加背景颜色,但是这个处理起来有没麻烦,并且一个项目不过能只有那么一个button需要添加这个状态颜色,所以自己也常试封装一个button的背景颜色,上代码,如果哪位大神有好的建议也希望能告诉我,直接留言,谢谢

 

//这是继承UIButton的扩展类

//UIButton+MHFillColor.h

#import <UIKit/UIKit.h>

 

@interface UIButton (MHFillColor)

 

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

 

@end

 

 

 

//UIButton+MHFillColor.m

#import "UIButton+MHFillColor.h"

 

@implementation UIButton (MHFillColor)

 

- (void)ym_setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state

{

    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];

}

 

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

{

    CGRect rect = CGRectMake(0.0, 0.0, 1.0, 1.0);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    

    CGContextSetFillColorWithColor(context, [color CGColor]);

    CGContextFillRect(context, rect);

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return image;

}

 

@end

原文地址:https://www.cnblogs.com/ljj-Andrew-519/p/7128785.html