一、UIAppearance
1、這是一個可以改變默認屬性的類
2、可以顯示的控件都可以使用這個類提供的方法來改變默認的顯示屬性。比如背景色、字體大小等等。
3、使用此類的方法時要慎重,因爲改變了屬性,就相當於把某個類下的所有實例對象的屬性改變了,影響的是整個工程。
二、常用的兩個方法
1、+ (instancetype)appearance;
[[UIButton appearance] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];//只要創建button它的字體顏色都會爲紅色。改變了默認屬性
// [UIView appearance]
// [UIImageView appearance]
又如,改變導航條的默認屬性
[[UINavigationBar appearance] setTitleTextAttributes:@{
NSFontAttributeName:[UIFont systemFontOfSize:18],//改變默認字體
NSForegroundColorAttributeName:[UIColor cyanColor]//改變默認背景色
}];
改變某容器下面的某個類的默認屬性,相對appearance來說縮小了一定的範圍。
// 獲取當前類下面的UIBarButtonItem
UIButton *btnDefault = [UIButton appearanceWhenContainedIn:[UINavigationBar class], nil];
//設置導航條下按鈕正常狀態下的文字顏色
[btnDefault setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
UIButton的默認屬性改變了,但不是所有的button對象的屬性都會改變,只有這個buttonbn包含在avigationbar的子類時默認屬性纔會改變。
appearance:
1.父類改變了屬性。子類的屬性也會改變
比如:
[[UIButton appearance] setBackgroundColor:[UIColor blueColor]];
創建一個新類:
LKLButton : UIButton
實例化一個LKLButton,其默認的背景顏色爲藍色。
2、子類改變了屬性。不影響父類
[[LKLButton appearance] setBackgroundColor:[UIColor blueColor]];
實例化一個UIButton,其默認的背景顏色不會是藍色。
appearanceWhenContainedIn
1、只改變某個容器下的LKLButton
比如:
[[LKLButton appearanceWhenContainedIn:[OneViewController class], nil] setBackgroundColor:[UIColor blueColor]];
只有在OneViewController這個類下的LKLButton的背景色纔會改變。
2、假設兩個容器A與B,並且B:A;
[[LKLButton appearanceWhenContainedIn:[A class], nil] setBackgroundColor:[UIColor blueColor]];
那麼B容器下的LKLButton的背景色也會發生改變
參考文章: