Search code examples
iosobjective-cuiviewcontrolleruinavigationbaruicolor

How to set different navigationbar color for different UIViewcontroller in xib?


Iam trying to set different UINavigationBar color for different UIViewController in project.Till now i tried following code in ViewdidAppear methode of each UIViewController class and its not working still the color of navigationbar is not changing.

UIImage *navBackgroundImage = [UIImage imageNamed:@"redbar.png"];
    [[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];

Please help me


Solution

  • Try

    [[UINavigationBar appearance] setBarTintColor: [UIColor redColor]];
    

    Or, on iOS 6,

    [[UINavigationBar appearance] setTintColor:[UIColor redColor]];
    

    If you have a navigation controller as rootViewController, get it with:

        UINavigationController* nc = (UINavigationController*)[[[UIApplication sharedApplication] delegate] window].rootViewController;
    

    And then set the color:

    [nc.navigationBar setBarTintColor:[UIColor redColor]];
    

    And if you want to change the color in each viewcontroller, just put the code in each viewWillAppear method

    If you don't want to override the viewWillAppearin every viewcontroller, you can create a super viewcontroller for your project. But if it's too late, you can also create a custom UINavigationController and simply override push/pop methods like:

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

    Do this for the four methods:

    - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
    - (UIViewController *)popViewControllerAnimated:(BOOL)animated;
    - (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated;
    - (NSArray *)popToRootViewControllerAnimated:(BOOL)animated;
    

    Or at least for the methods you use. And then override viewWillAppear in your viewControllers which need another bar color.