Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Background Image on UINavigationBar

My app uses a navigation controller with an image on in the navigation bar of the home page. The background image is done by putting

[navigationController.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
[_window addSubview:navigationController.view];

in the app delegate. The nav bar displays this image fine.

Every other view will not have an image in the navigation bar. Therefore, I need to remove this background image when any other view controller is pushed. Does anyone know how this can be done?

There are many answers online about adding or changing a nav bar image, but this question is a little bit different. Thank you in advance.

like image 330
alexshafran Avatar asked Jan 13 '12 03:01

alexshafran


2 Answers

To remove UINavigationBar background in iOS 5 or later, you should do this:

[navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];

Hope it helps

like image 100
Timur Mustafaev Avatar answered Sep 28 '22 09:09

Timur Mustafaev


I believe this to be the first actual answer to this for iOS5, the main problem being the "removal" of the background image once you are done. Well, just retain the existing image and put it back when you are done.

@implementation MyViewController {
    UIImage *_defaultImage;
}

- (void)viewWillAppear:(BOOL)animated {   
    _defaultImage = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar.png"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController.navigationBar setBackgroundImage:_defaultImage forBarMetrics:UIBarMetricsDefault];
}
like image 36
Pork 'n' Bunny Avatar answered Sep 28 '22 10:09

Pork 'n' Bunny