一、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的背景色也会发生改变
参考文章: