在開發(fā)中經(jīng)常遇到要多次重復(fù)需求,此時(shí)用appearance可以大大簡化工作量,但是appearance使用的前提是,該類已經(jīng)遵守@protocol UIAppearance <NSObject>協(xié)議,并且實(shí)現(xiàn)+ (instancetype)appearance方法.
// 設(shè)置整個(gè)應(yīng)用中的 UITabBarItem 按鈕的顏色
UITabBarItem *item = [UITabBarItem appearance];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor blackColor];
[item setTitleTextAttributes:attrs forState:UIControlStateSelected];
// 設(shè)置字體的尺寸:只有正常狀態(tài)下設(shè)置才有效果
NSMutableDictionary *attrsNor = [NSMutableDictionary dictionary];
attrsNor[NSFontAttributeName] = [UIFont systemFontOfSize:13];
[item setTitleTextAttributes:attrsNor forState:UIControlStateNormal];
appearance和appearanceWhenContainedIn的區(qū)別:appearance使用要慎重,因?yàn)閍ppearance是獲取的整個(gè)應(yīng)用中的,很可能一不小心就把其他地方的也改了,使用appearanceWhenContainedIn就會(huì)相對(duì)較安全,它只會(huì)統(tǒng)一修改制定類里面的屬性
// 設(shè)置某各類中的 UITabBarItem 按鈕的顏色
UITabBarItem *item = [UITabBarItem appearanceWhenContainedIn:self, nil];
NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
attrs[NSForegroundColorAttributeName] = [UIColor blackColor];
[item setTitleTextAttributes:attrs forState:UIControlStateSelected];
appearance使用注意:
- 一定要在控件顯示之前設(shè)置才有用,一般會(huì)放在+ (void)load方法中而不放在+(void)initialize中,因?yàn)? (void)load方法只會(huì)調(diào)用一次,+(void)initialize可能會(huì)調(diào)用多次,使用時(shí)還需要判斷:
+ (void)initialize
{
if (self == [LHLTabBarController class]) {
}
}
- 只有被UI_APPEARANCE_SELECTOR宏修飾的屬性,才能使用appearance統(tǒng)一設(shè)置
- (void)setTitleTextAttributes:(nullable NSDictionary<NSString *,id> *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。