在开发项目的时候,项目中使用的UINavigationController可能有很多,如何快速设置整个项目中的UINavigationBar的标题以及UINavigationBar上的按钮的样式呢?
设置UINavigationBar标题主题
// 设置UINavigationBar的主题,只要使用了该UINavigationController,都会被统一设置
UINavigationBar *bar = [UINavigationBar appearance];
// 设置整个项目中的导航栏背景图片
// [bar setBackgroundImage:<#(nullable UIImage *)#> forBarPosition:<#(UIBarPosition)#> barMetrics:<#(UIBarMetrics)#>];// 与设备的横竖屏有关
[bar setBackgroundImage:[UIImage imageNamed:@"navigationbar.png"] forBarMetrics:UIBarMetricsDefault];
// 设置UINavigationBar上的所有文字属性
// 设置文字属性
NSMutableDictionary *barTextAttrs = [NSMutableDictionary dictionary];
barTextAttrs[UITextAttributeTextColor] = [UIColor whiteColor];
// UITextAttributeFont --> NSFontAttributeName(iOS7)
#warning 过期 : 并不代表不能用, 仅仅是有最新的方案可以取代它
barTextAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:21.0];
// UIOffsetZero是结构体, 只要包装成NSValue对象, 才能放进字典\数组中
barTextAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetZero];
[bar setTitleTextAttributes:barTextAttrs];
设置UINavigationBar上的按钮主题样式
// 设置项目所有UIBarButtonItem的主题
// 通过appearance对象能修改整个项目中所有UIBarButtonItem的样式
UIBarButtonItem *appearance = [UIBarButtonItem appearance];
/**设置文字属性**/
// 设置普通状态的文字属性
NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
textAttrs[UITextAttributeTextColor] = [UIColor orangeColor];
textAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:15];
textAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetZero];
[appearance setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
// 设置高亮状态的文字属性
NSMutableDictionary *highTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
highTextAttrs[UITextAttributeTextColor] = [UIColor blueColor];
[appearance setTitleTextAttributes:highTextAttrs forState:UIControlStateHighlighted];
// 设置不可用状态(disable)的文字属性
NSMutableDictionary *disableTextAttrs = [NSMutableDictionary dictionaryWithDictionary:textAttrs];
disableTextAttrs[UITextAttributeTextColor] = [UIColor lightGrayColor];
[appearance setTitleTextAttributes:disableTextAttrs forState:UIControlStateDisabled];
/**设置按钮背景**/
// 技巧: 为了让某个按钮的背景消失, 可以设置一张完全透明的背景图片
[appearance setBackgroundImage:[UIImage imageNamed:@"navigationbar_button_background"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
如果设置了UIToolBar的键盘上有按钮(UIBarButtonItem类型),UIBarButtonItem主题设置后,也会对UIToolBar的按钮有效果,即该设置对项目中的所有UIBarButtonItem有效。