Search code examples
iosbackgrounduinavigationbarupdatesuiappearance

Updating navigation bar after a change using UIAppearance


I'm currently customising the navigation bar background image of my iOS app using the UIAppearance proxy. There is a button for switching between two different modes which triggers a notification. This notification will change the background to a different image using again the proxy. My problem is that this change becomes visible only when I go to a different controller and I come back to it. I'm not able to force the update of the navigation bar within the controller.

I've tried this in my MainTabBarController:

- (void) onAppChangedMode: (NSNotification*)notif {

APP_MODE mode = (APP_MODE) [[notif object] integerValue];

// change navigation bar appearance
[[UILabel appearance] setHighlightedTextColor:[UIColor redColor]];
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:(mode == 0 ? @"navbar.png" : @"navbar2.png")] forBarMetrics:UIBarMetricsDefault];
// trying to update
for (UIViewController* vc in self.viewControllers) {
     [vc.navigationController.navigationBar setNeedsDisplay];
}

}

but nothing...it's not working. Any idea how to achieve it?

Thanks!


Solution

  • Try this code to change the background image for the current nav bar only:

    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    

    Use the above code after changing the UIAppearance. This will force a change in the nav bar of the current controller. The nav bars for the other controllers will be handled by the change in UIAppearance.