views:

75

answers:

1
UIImageView *navBarImageView = [[UIImageView alloc] initWithImage:navBarImage];
[navBarImageView setFrame:CGRectMake(0, 0, 320, 44)];
self.navigationItem.titleView = navBarImageView;
[navBarImageView release];

I am trying to add an image to my navigationBar, but when I used the code as listed above, it places the image into the navigationBar but leaves a grey gap to the left and right of the image. The image was created at 320x44, I'm not sure why it is resizing it despite the fact that I am setting the frame.

+2  A: 

That's... probably not how you want to do that—it's not what the titleView is for. The usual way to do a custom navigation-bar background is to create a category on UINavigationBar, like so:

 @implementation UINavigationBar(MyCustomBackground)
 - (void)drawRect:(CGRect)r
 {
      [[UIImage imageNamed:@"my-navigation-background.png"] drawInRect:self.bounds];
 }
 @end

Throw that in a .m file in your project and you should see all of your navigation bars use "my-navigation-background.png" as their background.

Noah Witherspoon
Well, I don't really want it to be for all navigation bars. I have a different navigation bar for the child screens. Can I specify it per screen?
Chris
Sure. Set the bars' `tag` property to a unique value for each different image you want to use, then check `self.tag` in the category's `-drawRect:` and draw the appropriate image.
Noah Witherspoon
It's working. Only problem is when I go back to the first screen, it seems to be keeping the tag from the child screen and showing the child screen navBar.
Chris
Yeah, it's probably only getting set when you create the child controller. The navigation bar persists from view to view, after all. You'll probably have better results setting the tag in `-viewWillAppear:`—from both controllers—and then calling `-setNeedsDisplay` on the bar.
Noah Witherspoon
I'm calling [self.navigationController.navigationBar setNeedsDisplay]; but nothing is happening.
Chris
I got it - I was calling viewDidAppear incorrectly, did not have the :(BOOL)animatedThank You
Chris