iOS button点击点击状态下改变背景颜色

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

//添加image分类  .h文件代码
#import "UIImage+Extension.h"

@implementation UIImage (Extension)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGFloat imageW = 3;
    CGFloat imageH = 3;
    // 1.开启基于位图的图形上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageW, imageH), NO, 0.0);
    // 2.画一个color颜色的矩形框
    [color set];
    UIRectFill(CGRectMake(0, 0, imageW, imageH));
    
    // 3.拿到图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    // 4.关闭上下文
    UIGraphicsEndImageContext();
    
    return image;
}

@end


//image分类  .m文件代码

#import <UIKit/UIKit.h>

@interface UIImage (Extension)

/**
 *  生成的图片的rect默认为100,100
 */
+ (UIImage *)imageWithColor:(UIColor *)color;
@end

//导入头文件   调用  分类方法   可改变image背景颜色
   


 UIButton *loginButton = [[UIButton alloc]initWithFrame:self.view.bounds];
    [loginButton setTitle:@"登 录" forState:UIControlStateNormal];
    loginButton.backgroundColor = [UIColor whiteColor];
    [loginButton setBackgroundImage:[UIImage imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateHighlighted];
    [self.view addSubview:loginButton];