iOS5及其以后提供了一个比较强大的工具UIAppearance,我们通过UIAppearance设置一些UI的全局效果,这样就可以很方便的实现UI的自定义效果又能最简单的实现统一界面风格,它提供如下两个方法。
+ (id)appearance
// 这个方法是统一全部改,比如你设置UINavBar的tintColor,你可以这样写:[[UINavigationBar appearance] setTintColor:myColor];
+ (id)appearanceWhenContainedIn:(Class )ContainerClass,...
//这个方法可设置某个类的改变:例如:设置UIBarButtonItem 在UINavigationBar、UIPopoverController、UITabbar中的效果。就可以这样写
//[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], [UIPopoverController class],[UITabbar class] nil] setTintColor:myPopoverNavBarColor];
UIAppearance实现原理
在通过UIAppearance调用“UI_APPEARANCE_SELECTOR”标记的方法来配置外观时,UIAppearance实际上没有进行任何实际调用,而是把这个调用保存起来(在Objc中可以用NSInvocation对象来保存一个调用)。当实际的对象显示之前(添加到窗口上,drawRect:之前),就会对这个对象调用之前保存的调用。当这个setter调用后,你的界面风格自定义就完成了。
如何使用UIAppearance
(1)必须遵守UIAppearance协议。
打开UIView的头文件,可以看到UIView的协议中包含UIAppearance协议:
NS_CLASS_AVAILABLE_IOS(2_0) @interface UIView : UIResponder
所有继承UIView的控件都可以使用Appearance设置UI全局效果。
(2)属性后面必须带有UI_APPEARANCE_SELECTOR
同样还是UIView的头文件,可以看到backgroundColor的后面有UI_APPEARANCE_SELECTOR,表明这个属性是可以用Appearance自定义全局外观的。
@property(nullable, nonatomic,copy) UIColor *backgroundColor UI_APPEARANCE_SELECTOR; // default is nil. Can be useful with the appearance proxy on custom UIView subclasses.