有这样的一类简单需求: UIButton的背景色要与其state相关, 如未点击时显示蓝色, 点击时显示绿色.
但是, UIButton自身并未提供setBackgroundColor:forState:方法, 因此我们不得不单独在touchDown等方法中去更新其backgroundColor属性.
这里介绍如何为UIButton提供该扩展方法, Objective-C和Swift的版本都有.
其中用到了runtime的关联对象, 不熟悉的同学可以先参考iOS — 理解Runtime机制及其使用场景.
Objective-C
Objective-C中通过Category提供该扩展方法.
头文件:
#import <UIKit/UIKit.h>
@interface UIButton (CS_BackgroundColor)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state;
@end
实现文件:
#import "UIButton+CS_BackgroundColor.h"
#import <objc/runtime.h>
@interface UIButton (CS_BackgroundColor)
@property (nonatomic, strong) NSMutableDictionary *cs_dictBackgroundColor;
@end
@implementation UIButton (CS_BackgroundColor)
static const NSString *key_cs_backgroundColor = @"key_cs_backgroundColor";
static NSString *cs_stringForUIControlStateNormal = @"cs_stringForUIControlStateNormal&#