在开发中经常遇到要多次重复需求,此时用appearance可以大大简化工作量,但是appearance使用的前提是,该类已经遵守@protocol UIAppearance <NSObject>协议,并且实现+ (instancetype)appearance方法.
// 设置整个应用中的 UITabBarItem 按钮的颜色
UITabBarItem *item = [UITabBarItem appearance];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor blackColor];
[item setTitleTextAttributes:attrs forState:UIControlStateSelected];
// 设置字体的尺寸:只有正常状态下设置才有效果
NSMutableDictionary *attrsNor = [NSMutableDictionary dictionary];
attrsNor[NSFontAttributeName] = [UIFont systemFontOfSize:13];
[item setTitleTextAttributes:attrsNor forState:UIControlStateNormal];
appearance和appearanceWhenContainedIn的区别:appearance使用要慎重,因为appearance是获取的整个应用中的,很可能一不小心就把其他地方的也改了,使用appearanceWhenContainedIn就会相对较安全,它只会统一修改制定类里面的属性
// 设置某各类中的 UITabBarItem 按钮的颜色
UITabBarItem *item = [UITabBarItem appearanceWhenContainedIn:self, nil];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor blackColor];
[item setTitleTextAttributes:attrs forState:UIControlStateSelected];
appearance使用注意:
- 一定要在控件显示之前设置才有用,一般会放在+ (void)load方法中而不放在+(void)initialize中,因为+ (void)load方法只会调用一次,+(void)initialize可能会调用多次,使用时还需要判断:
+ (void)initialize
{
if (self == [LHLTabBarController class]) {
}
}
- 只有被UI_APPEARANCE_SELECTOR宏修饰的属性,才能使用appearance统一设置
- (void)setTitleTextAttributes:(nullable NSDictionary<NSString *,id> *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;