0

I have successfully added a background image to my UINavigationBar with the following code:

    UIImageView *barView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"subHeader_lg.png"]];
    [calculatorBar addSubview:barView];

    [barView release];

However, with this method, the title of the view is covered by the image.

enter image description here

If I navigate further into the app, and then back, the title appears on top of the background image like so:

enter image description here

Any ideas how I can get the title to appear on top from the beginning?

I have tried pushing the barView to the back, but that makes it hidden behind everything else.

EDIT:

It seems that the custom draw function is the accepted answer, but I am unable to get the draw function to be called. I have this code at the bottom of my appdelegate.m file

@implementation UINavigationBar (UINavigationBarCustomDraw)

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

@end
Dan F
  • 17,654
  • 5
  • 72
  • 110
  • Looks like this guy had a similar problem, but the answer was a bit more involved than the one you have. http://stackoverflow.com/questions/979750/background-image-for-navigation-view-iphone/2046393#2046393 – Pixelmixer Nov 07 '11 at 20:32

2 Answers2

1

When you call "addSubview" it adds it above any view that have already been added, thus covering the title.

What you want is

[calculatorBar insertSubview:barView atIndex:0];

However, this won't make it "stick" on subsequent pushes, so use the methods described at http://www.developers-life.com/custom-uinavigationbar-with-image-and-back-button.html for a better solution.

Also in iOS 5, Apple has added a built in way to customize the nav bar see http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIAppearance_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40010906

Christian Schlensker
  • 21,708
  • 19
  • 73
  • 121
1

To set the background image on your navigation bar, use the following.

On iOS 5.x, use [calculatorBar setBackgroundImage: barView.image forBarMetrics: 0];

On iOS 4.x use calculatorBar.layer.contents = (id)barView.image.CGImage;

greenhorn
  • 1,097
  • 6
  • 10