首页 > 代码库 > iOS 自定义各类bar的属性

iOS 自定义各类bar的属性

  在iOS应用开发中,经常需要为导航栏和标签栏设置相同的主题,一个一个去设置的话,就太麻烦了,可以通过对应用中所有的导航栏和标签栏同意设置背景、字体等属性。

  如:创建一个继承自“UINavigationController”的公共父类,然后应用中所有的NavigationController都继承UINavigationController,通过在UINavigationController类中的类方法

initialize中对导航栏属性进行设置,就会对项目中所有的导航栏控制器起作用

  示例代码如下:

 1 + (void)initialize 2 { 3      4 #warning  可以通过设置UITabBar主题的方式来修改UITabBar中按钮的颜色 5     UITabBar *tabBar = [UITabBar appearance]; 6     NSMutableDictionary *tabAttrs = [NSMutableDictionary dictionary]; 7     tabAttrs[UITextAttributeTextColor] = [UIColor orangeColor]; 8     [tabBar setTintColor:[UIColor orangeColor]]; 9     10     // 1 设置UINavigationBar11     UINavigationBar *navBar = [UINavigationBar appearance];12 13     14     15     //1.1 设置状态栏16     [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;17     18     //1.2 设置背景图片19         [navBar setBackgroundImage:[UIImage imageWithName:@"navigationbar_background"] forBarMetrics:UIBarMetricsDefault];20   21     22     //1.3.设置字体23     NSMutableDictionary *attrs = [NSMutableDictionary dictionary];24     attrs[UITextAttributeTextColor] = [UIColor blackColor];25     attrs[UITextAttributeTextShadowOffset] = [NSValue valueWithCGSize:CGSizeMake(0, 0)];26     attrs[UITextAttributeFont] = [UIFont systemFontOfSize:20];27 28     [navBar setTitleTextAttributes:attrs];29     30     //2 设置导航条按钮主题31     UIBarButtonItem *barItem = [UIBarButtonItem appearance];32     //2.1 设置背景图33     [barItem setBackButtonBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];34     [barItem setBackButtonBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background_pushed"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];35     [barItem setBackButtonBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background_disable"] forState:UIControlStateDisabled barMetrics:UIBarMetricsDefault];36     //2.2 设置字体属性37     NSMutableDictionary *itemAttrs = [NSMutableDictionary dictionary];38 39     itemAttrs[UITextAttributeTextColor] = iOS7 ? [UIColor orangeColor] : [UIColor blackColor];40     itemAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithCGSize:CGSizeMake(0, 0)];41     itemAttrs[UITextAttributeFont] = [UIFont systemFontOfSize:14];42     [barItem setTitleTextAttributes:itemAttrs forState:UIControlStateNormal];43 }

 

iOS 自定义各类bar的属性