如何在xib中为不同的UIViewcontroller设置不同的导航栏颜色?

Nav*_*mar 10 objective-c uinavigationbar uiviewcontroller uicolor ios

我试图在项目中为不同的UIViewController设置不同的UINavigationBar颜色.现在我尝试在每个UIViewController类的ViewdidAppear方法中跟随代码并且它不工作仍然导航栏的颜色没有改变.

UIImage *navBackgroundImage = [UIImage imageNamed:@"redbar.png"];
    [[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];
Run Code Online (Sandbox Code Playgroud)

请帮我

Y.B*_*ons 12

尝试

[[UINavigationBar appearance] setBarTintColor: [UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

或者,在iOS 6上,

[[UINavigationBar appearance] setTintColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

如果你有一个导航控制器作为rootViewController,得到它:

    UINavigationController* nc = (UINavigationController*)[[[UIApplication sharedApplication] delegate] window].rootViewController;
Run Code Online (Sandbox Code Playgroud)

然后设置颜色:

[nc.navigationBar setBarTintColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)

如果你想改变每个viewcontroller中的颜色,只需将代码放在每个viewWillAppear方法中

如果您不想覆盖viewWillAppear每个视图控制器,可以为项目创建超级视图控制器.但如果为时已晚,您还可以创建自定义UINavigationController并简单地覆盖推送/弹出方法,如:

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [super pushViewController:viewController animated:animated];
    [self.navigationBar setBarTintColor:[UIColor redColor]];
}
Run Code Online (Sandbox Code Playgroud)

为四种方法执行此操作:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (UIViewController *)popViewControllerAnimated:(BOOL)animated;
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated;
Run Code Online (Sandbox Code Playgroud)

或者至少对你使用的方法.然后viewWillAppear在需要另一个条形颜色的viewControllers中覆盖.