Search code examples
objective-cioscocoa-touchios5

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!


Solution

  • 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.