amitsbajaj
amitsbajaj

Reputation: 1304

UINavigationBar custom background image applied in one view controller and then affecting every single view controller in the app

I am working with themes in my app. Each theme comes with a custom navigation bar. As a default, I have applied a custom navigation bar in my AppDelegate:

[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
UIImage *navBackgroundImage = [UIImage imageNamed:@"purplynav.png"];
[[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];

If I go to a specific Table View Controller in my app and in the viewWillAppear, I put:

if ([self.selectedTheme isEqualToString:@"Blur"])
{
    UIImage *navBackgroundImage = [UIImage imageNamed:@"pastelpinknav.png"];
    [[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];
}

The "pastelpinknav" suddenly gets applied to every single navigation bar in my app, even though I'm only setting it in this one Table View Controller.

How do I set it so that the navigation bar only applies to this one view controller when set, but is still set to default in the App Delegate when a theme is not set?

Thanks in advance!

Upvotes: 1

Views: 1414

Answers (2)

Aviel Gross
Aviel Gross

Reputation: 9975

From your view controller call:

[[UINavigationBar appearanceWhenContainedIn:[self class], nil] setBackgroundImage:navBackgroundImage
                                                                    forBarMetrics:UIBarMetricsDefault];

Explenation:

This will change the foo color of the entire app:

[[UINavigationBar appearance] setFooColor:@"blue"]

In order to change appearance of specific container (i.e your view controller), you need to implement UIAppearanceContainer and then call (UIViewController already implements it):

[UINavigationBar appearanceWhenContainedIn:(Class<UIAppearanceContainer>), ..., nil]

Upvotes: 1

Venk
Venk

Reputation: 5955

You have to change again the navigationBar image in viewWillDisappear

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

Because you are using [UINavigationBar appearance] it will commonly changes the UINavigationBar appearance.

Upvotes: 3

Related Questions