Nick ONeill Nick ONeill - 1 year ago 129
Objective-C Question

UINavigationBar setBackgroundImage: forBarMetrics: Not Working

I just switched over to iOS 5 and everything appears to be working in my application aside from the custom navigation bar. I looked around and followed everybody's suggestion of calling the new methods setBackgroundImage: forBarMetrics: however it doesn't appear to work. This is the code I've tried to place both within the app delegate and within the viewDidLoad method of some of the view controllers:

UINavigationBar *nb = [[UINavigationBar alloc]init];
if( [nb respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] )
UIImage *image = [UIImage imageNamed:@"navBarBackground.png"];
[nb setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
[nb release];

Unfortunately this doesn't work. If anybody has any suggestions at all, I'm all ears!

Answer Source

To apply image to all your navigation bars, use the appearance proxy:

[[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

For an individual bar:

// Assuming "self" is a view controller pushed on to a UINavigationController stack
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

In your example, the background image won't change because nb isn't hooked up to anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download