A.导航栏两侧文字按钮
1.需求:
所有导航栏两侧的文字式按钮统一样式
普通样式:橙色
高亮样式:红色
不可用样式:亮灰
阴影:不使用
字体大小:15
github:https://github.com/hellovoidworld/HVWWeibo
2.实现效果
默认样式:
统一使用样式:
3.思路
在创建item的时候逐个设置:代码超级冗余抽取创建公共父类:稍好的选择,但是继承了此公共父类的控制器,就不能操作其去继承系统自带的控制器类了,造成很大的隐患。iOS中控制器不建议提取公共父类,最好直接继承系统自带控制器。使用主题appearance统一设置所有UIBarButtonItem的样式:采用!在自定义的UINavigationController的类初始化方法中实现一次,就可以改变所有使用了此类的BarButtonItem样式
4.实现
HVWNavigationViewController.m:
1/** 类初始化的时候调用*/2+ (void)initialize {3//初始化导航栏样式4[self initNavigationBarTheme];56//初始化导航栏item样式7[self initBarButtonItemTheme];8}910/** 统一设置导航栏item的样式11* 因为是通过主题appearence统一修改所有NavivationBar的样式,可以使用类方法12*/13+ (void) initBarButtonItemTheme {14//设置导航栏,修改所有UINavigationBar的样式15UIBarButtonItem *appearance =[UIBarButtonItem appearance];1617//设置noraml状态下的样式18NSMutableDictionary *normalTextAttr =[NSMutableDictionary dictionary];19//字体大小20normalTextAttr[NSFontAttributeName] = [UIFont systemFontOfSize:15];21//字体颜色22normalTextAttr[NSForegroundColorAttributeName] =[UIColor orangeColor];23//设置为normal样式24[appearance setTitleTextAttributes:normalTextAttr forState:UIControlStateNormal];2526//设置highlighted状态下的样式27NSMutableDictionary *highlightedTextAttr =[NSMutableDictionary dictionaryWithDictionary:normalTextAttr];28//字体颜色29highlightedTextAttr[NSForegroundColorAttributeName] =[UIColor redColor];30//设置为normal样式31[appearance setTitleTextAttributes:highlightedTextAttr forState:UIControlStateHighlighted];3233//设置disabled状态下的样式34NSMutableDictionary *disabledTextAttr =[NSMutableDictionary dictionaryWithDictionary:normalTextAttr];35//字体颜色36disabledTextAttr[NSForegroundColorAttributeName] =[UIColor lightGrayColor];37//设置为normal样式38[appearance setTitleTextAttributes:disabledTextAttr forState:UIControlStateDisabled];3940}
B.设置导航栏样式
1.需求:
统一显示文字颜色:黑色文字阴影:禁止字体大小:20
2.思路:同“A”
3.实现:
同“A"
HVWNavigationViewController.m:
1/** 统一设置导航栏样式*/2+ (void) initNavigationBarTheme {3//使用appearence(主题)设置,统一修改所有导航栏样式4UINavigationBar *appearance =[UINavigationBar appearance];56//为了统一iOS6和iOS7,iOS6需要设置导航栏背景来模拟iOS7的效果7if(!iOS7) {8[appearance setBackgroundImage:[UIImage imageWithNamed:@"navigationbar_background"] forBarMetrics:UIBarMetricsDefault];9}1011//设置属性12NSMutableDictionary *attr =[NSMutableDictionary dictionary];13//设置字体14attr[NSForegroundColorAttributeName] =[UIColor blackColor];15attr[NSFontAttributeName] = [UIFont systemFontOfSize:20];16//消去文字阴影,设置阴影偏移为017NSShadow *shadow =[[NSShadow alloc] init];18shadow.shadowOffset =CGSizeZero;19attr[NSShadowAttributeName] =shadow;2021[appearance setTitleTextAttributes:attr];22}