学无止境橙红科技有限公司复制粘贴

UIAppearance与UI_APPEARANCE_SELEC

2016-09-26  本文已影响1400人  ac41d8480d04

在iOS 5之后,出现了两个Protocol,分别是UIAppearance 以及UIAppearanceContainer,通过这两个协议,我们可以在开发过程中规范对于UI的定制工作。

使用这两个Protocol,不仅可以简单更改定制各种外观样式,甚至还能制定出现在特定位置的时候才允许设置不同的UI外观特性。

UIAppearance Protocol主要使用一下两个方法:

+ (instancetype)appearance;
+ (instancetype)appearanceWhenContainedIn:(nullable Class <UIAppearanceContainer>)ContainerClass, ... NS_REQUIRES_NIL_TERMINATION NS_DEPRECATED_IOS(5_0, 9_0, "Use +appearanceWhenContainedInInstancesOfClasses: instead") __TVOS_PROHIBITED;

iOS 9之后,第二个方法替换为:
+ (instancetype)appearanceWhenContainedInInstancesOfClasses:(NSArray<Class <UIAppearanceContainer>> *)containerTypes NS_AVAILABLE_IOS(9_0);

使用之后,返回值接受者为使用此方法的实例,很多的UIView或者UIControl的属性都支持此项操作,比如 UIButton的TitleColor

- (void)setTitleColor:(nullable UIColor *)color forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default if nil. use opaque white

以及UIview的BackgroundColor

@property(nullable, nonatomic,copy)            UIColor          *backgroundColor UI_APPEARANCE_SELECTOR; // default is nil. Can be useful with the appearance proxy on custom UIView subclasses.

上面两个例子,大家可以看出,只有标记了UI_APPEARANCE_SELECTOR宏定义的方法,才会遵循UIAppearance Protocol,并允许使用协议方法。

使用范例:

[[UINavigationBar appearance] setBarTintColor:myNavBarBackgroundColor];

或者

[[UIBarButtonItem appearanceWhenContainedIn:[NSArray arrayWithObject:[UINavigationBar class]]
   setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:state barMetrics:metrics];

只要是遵循了UIAppearanceContainer Protocol的类,比如UINavigatorBarUIPopOverController等,都是此容器类,可以使用协议中的方法。

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读