给UIButton设置BackgroundColor:forState

1,622 阅读1分钟

洲洲哥在写这篇文章的时候,我想起了之前写过的一篇文章 《 iOS给UIButton添加一个新的属性》,大家在读这篇文章前可以先复习一下哦。。。。

今天带来的就是利用延展做一个偷懒的事情。。 在开发过程中要设置一个uibutton的背景颜色并且要分当前按钮的状态的时候。那写的就是相当费劲的。不过哥吃饱了。这种费力讨好的事情 就让洲洲哥代劳吧!!!

废话不多说,上代码。。。<各位此处应该有笑声,,如果有请持续5秒钟> 先看看 利用这个延展的调用代码:


 [self.itemBtn setBackgroundColor:YSColor(254, 245, 245) forState:UIControlStateNormal];
 [self.itemBtn setBackgroundColor:YSColor(252, 94, 94) forState:UIControlStateSelected];

和我们平常设置button的时候一样,so easy

  [self.itemBtn setTitleColor:YSColor(110, 110, 110) forState:UIControlStateNormal];
  [self.itemBtn setTitleColor:YSColor(255, 255, 255) forState:UIControlStateSelected];

下面开始展示代码咯 添加一个延展名字当然是对uibutton的延展咯(这里同时也对button添加了一个titleNmae的属性)

首先看.h文件的写法

#import <UIKit/UIKit.h>

@interface UIButton (FillColor)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;

@property (nonatomic, strong) NSString * titleName;
@end

下面是.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

上面就是咯,掌声吧各位。