Ios – Changing the UINavigationBar background image

iosiphoneuinavigationbaruinavigationcontroller

I've been trying to change the background image of the UINavigationBar of my application. I tried several ways. First I added to my AppDelegate class the following code:

@implementation UINavigationBar (CustomImage)
    - (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"navigationbar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

But it wasn't working. My next try was to write a CustomizedNavigationBar Class which is overriding the drawRect method. It looked like that:

CustomizedNavigationBar.h

#import <UIKit/UIKit.h>

@interface CustomizedNavigationBar : UINavigationBar

@end

CustomizedNavigationBar.m

#import "CustomizedNavigationBar.h"

@implementation CustomizedNavigationBar

- (void) drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed: @"navigationbar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

    NSLog(@"I got called!!!!!");
}

@end

In my .xib file where the NavigationBar is defined I changed the class to the new CustomizedNavigationBar. But still it is not working..

As another test I downloaded an example project where the background image should be changed. But even with that sample code it was not working.

What am I doing wrong? I am using IOS 5. Any suggestions or other ways I could define a background image?

Thanks for your answers!

Best Answer

Starting in iOS 5 you should use the -setBackgroundImage:forBarMetrics: method:

[myNavbar setBackgroundImage:[UIImage imageNamed: @"UINavigationBarBackground.png"] 
               forBarMetrics:UIBarMetricsDefault];

And in Swift 4:

navigationBar.setBackgroundImage(UIImage(named: "UINavigationBarBackground.png"),
               for: .default)