Add background image to Navigation Bar

After iOS 5.0

iOS 5.0 made it so easy to set the navigation bar background image:

- (id) initWithRootViewController:(UIViewController *)rootViewController navigationBarBackgroundImage:(UIImage *)backgroundImage

  self = [super initWithRootViewController:rootViewController];


    if (backgroundImage != nil){
#ifdef __IPHONE_5_0 
        if ([[self navigationBar] respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
          [[self navigationBar] setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault]; 


  return self;


Before iOS 5.0

Recently I was asked to add a pale (off-white) color as the background color of a navigation bar, which I thought would just be a case of updating the tintColor property . However when I did this instead of getting the gradient effect that we were after all i ended up with was a solid off-white color.

Using a category I decided to override the drawRect method in UINavigationBar and set the background as an image (with gradient).


@interface UINavigationBar (BackgroundNavigationBar)


@implementation UINavigationBar (BackgroundNavigationBar)

- (void) drawRect:(CGRect)rect {
    UIImage *barImage = [UIImage imageNamed:@"navigation_bar_gradient.png"];
    [barImage drawInRect:rect];