Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 972
Nick ONeill Avatar asked Oct 13 '11 21:10

Nick ONeill


2 Answers

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.

like image 159
Rob Bajorek Avatar answered Nov 15 '22 16:11

Rob Bajorek


Answer by rob is correct but if application runs on iOS 4.3 or lower app will crash. So you can implement this like

if([[UINavigationBar class] respondsToSelector:@selector(appearance)]) //iOS >=5.0
{
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBar-Landscape.png"] forBarMetrics:UIBarMetricsLandscapePhone];   

}

This will set image for both mode Landscape and Portrait

like image 35
Kamleshwar Avatar answered Nov 15 '22 18:11

Kamleshwar