iOS开发之UINavigationBar主题设置

在开发项目的时候,项目中使用的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有效。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值