因为需求提出需要,UI要有两种模式。
模式A 模式B
这就需要美工为每个按钮提供4张图,即:模式A按钮normal状态、按钮display状态,模式B按钮normal状态、按钮display状态。
- 为UIButton添加两个属性tintNormalColor和tintDisabledColor,分别用于Normal和Disabled情况下的使用。根据实际情况,也可以添加Select等等
@interface UIButton (YourName)
@property(nonatomic,strong) UIColor *tintNormalColor;
@property(nonatomic,strong) UIColor *tintDisabledColor;
@end
- 使用objc_getAssociatedObject和objc_getAssociatedObject为分类增加属性。
再重写SetEnabled的方法,使UIButton在工作的时候可以自动调用刚刚添加的两个属性。
#import "UIButton+YourName.h"
static const char TintNormalColor_KEY;
static const char TintDisabledColor_KEY;
@implementation UIButton (YourName)
+ (void)load
{
Method systemMethod = class_getInstanceMethod([UIButton class], @selector(setEnabled:));
Method myMethod = class_getInstanceMethod([UIButton class], @selector(WS_SetEnabled:));
//2.进行方法的交换
method_exchangeImplementations(systemMethod, myMethod);
}
- (void)WS_SetEnabled:(BOOL)enabled
{
if (enabled) {
self.tintColor = self.tintNormalColor;
}else{
self.tintColor = self.tintDisabledColor;
}
[self WS_SetEnabled:enabled];
}
- (void)setTintNormalColor:(UIColor *)tintNormalColor
{
if (self.isEnabled) {
self.tintColor = tintNormalColor;
}
objc_setAssociatedObject(self, &TintNormalColor_KEY, tintNormalColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIColor*)tintNormalColor
{
return objc_getAssociatedObject(self, &TintNormalColor_KEY);
}
- (void)setTintDisabledColor:(UIColor *)tintDisabledColor
{
if (!self.isEnabled) {
self.tintColor = tintDisabledColor;
}
objc_setAssociatedObject(self, &TintDisabledColor_KEY, tintDisabledColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIColor*)tintDisabledColor
{
return objc_getAssociatedObject(self, &TintDisabledColor_KEY);
}
@end
网友评论