您的位置:首页 > 移动开发

UIAppearance和UIAppearanceContainer的作用

2015-05-29 12:03 357 查看
一、 UIAppearance和UIAppearanceContainer的作用

从iOS 5开始,苹果通过两个协议(UIAppearance和UIAppearanceContainer)规范了对许多UIKit控件定制的支持。所有遵循UIAppearance协议的UI控件通过定制都可以呈现各种外观。不仅如此,UIAppearance协议甚至允许开发者基于控件所属的区域指定不同的外观。也就是说,当某个控件包含在特定视图中时,可以指定它的外观(如UIBarButtonItem的tintColor)。也可以获取该控件类的外观代理对象,用该代理定制外观来实现。

二、 例子

1. 要定制应用中所有条形按钮的颜色,可以在UIBarButtonItem的外观代理中设置tintColor:

[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];

2. 同样,可以根据内部包含的视图采用如下方法来定制控件的外观:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]

setTintColor:[UIColor redColor]];

第一个参数是以nil结尾的所有容器类的列表,包括UINavigatorBar、UIPopOverController等遵循UIAppearanceContainer协议的类。

从iOS 5开始,大多数UI元素都增加了对UIAppearance协议的支持。此外,iOS 5中类似于UISwitch的控件允许我们方便地将on开关的颜色变成设计师选定的颜色。

三、怎么确定哪些情况下能够通过UIKit的外观代理来定制所有元素(以及元素中的哪些属性)呢?

读头文件。打开对应的UIKit元素的头文件,其中所有带有UI_APPEARANCE_SELECTOR标记的属性都支持通过外观代理来定制。举个例子,UINavigationBar.h中的tintColor属性带有UI_APPEARANCE_SELECTOR标记:

@property(nonatomic,retain) UIColor *tintColor UI_APPEARANCE_SELECTOR;

意味着可以调用

[[UINavigationBar appearance] setTintColor:newColor];

请注意*使用appearance设置UI效果最好采用全局的设置,在所有界面初始化前开始设置,否则可能失效。

//字体
NSDictionary *textAttributes1 = @{UITextAttributeFont: [UIFont systemFontOfSize:18],
UITextAttributeTextColor: [UIColor blueColor],
UITextAttributeTextShadowColor: [UIColor whiteColor],
UITextAttributeTextShadowOffset: [NSValue valueWithCGSize:CGSizeMake(1, 1)]};

[appearance setTitleTextAttributes:textAttributes1 forState:1];

NSDictionary *textAttributes2 = @{UITextAttributeFont: [UIFont systemFontOfSize:18],
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeTextShadowColor: [UIColor blackColor],
UITextAttributeTextShadowOffset: [NSValue
valueWithCGSize:CGSizeMake(1, 1)]};

[appearance setTitleTextAttributes:textAttributes2 forState:0];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: