导航控制器全局和编程方式更改导航栏渐变色

21

这段代码可以改变应用程序中任何地方的UINavigationBar的颜色。但是,我注意到它不会改变由UINavigationController使用的UINavigationBarUIColor(我的UINavigationBar来自一个UIStoryboard)。

UIColor* navBarColor = [UIColor colorWithRed:arc4random()%100/100.0 
                                       green:arc4random()%100/100.0 
                                        blue:arc4random()%100/100.0 
                                       alpha:1];
[[UINavigationBar appearance] setTintColor:navBarColor];

[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackTranslucent];
[[UINavigationBar appearance] setAlpha:0.7];
有没有一种方式可以访问UINavigationController导航栏的appearance对象? 我知道如何设置单个控制器的色调,但我想全局控制它们的外观。

更新: 这是我的错误,该代码确实会更改所有UINavigationBarUIColor,但需要覆盖和取消覆盖根导航控制器(例如呈现模态视图控制器),然后它会用新的UIColors重新绘制自己!

谢谢!

4个回答

19

iOS 8现在可以通过以下方法设置色调颜色:

self.navigationController.navigationBar.barTintColor = [UIColor redColor];

15

您可以使用 appearance 代理全局更改条形颜色:

NSDictionary *textTitleOptions = 
[NSDictionary dictionaryWithObjectsAndKeys:[UIColor darkGrayColor], 
                                           UITextAttributeTextColor, 
                                           [UIColor whiteColor],  
                                           UITextAttributeTextShadowColor, nil];

[[UINavigationBar appearance] setTitleTextAttributes:textTitleOptions];
textTitleOptions = 
 [NSDictionary dictionaryWithObjectsAndKeys:[UIColor darkGrayColor], 
                                            UITextAttributeTextColor, nil];
[[UINavigationBar appearance] setTintColor:[UIColor redColor]];
[[UIToolbar appearance] setTintColor:[UIColor redColor]];
[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];

1
请注意,UITextAttributeTextColorUITextAttributeShadowColor已被弃用 - 请改用NSForegroundColorAttributeNameNSShadowAttributeName - thomers

14

当你声明 UINavigationController 时,尝试这样做:

UINavigationController *myNavController = 
[[UINavigationController alloc] initWithRootViewController:myRootViewController];
myNavController.navigationBar.tintColor = 
    [UIColor colorWithRed:arc4random() % 100 / 100.0f
                    green:arc4random() % 100 / 100.0f
                     blue:arc4random() % 100 / 100.0f
                    alpha:1.0f];

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接