views:

2323

answers:

4

Hi guys ! i want add an image background to my navigation bar like this :

alt text

what is the code ? thank you

ist it right ?

//set custom background image
UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NavigationBackground.png"]];
[self.navigationBar insertSubview:backgroundView atIndex:0];
[backgroundView release];
A: 

You could also add a category that extends the UINavigationBar class and override the drawRect: method in the category.

nduplessis
so that code is right ? i don't try yet ! :D
Momeks
It's hard to say. Where will you use it? You might need to bring the background image view to the front every time the bar is displayed
nduplessis
+2  A: 

Your code alone won't do it, you'll have to write a category in order for it to work. There are two approaches regarding the way you should do it: the first one involves making the image a subview of your UINavigationBar and re-bringing it to front in each of your UIViewController's viewDidAppear method. This however has been reported having some issues with covering the right UIBarButtonItem. The other method involves overriding - (void)drawRect:(CGRect)rect and drawing the image there. Both of these are extensively covered in this discussion.

luvieere
(this) link is very helpful, thanks
Jirapong
+4  A: 

Here's the code from the link @luvieere mentioned above.

@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
iwat
+1  A: 

easiest way is just set the navigationbar layer contents.

NSString *barBgPath = [[NSBundle mainBundle] pathForResource:@"mybgimage" ofType:@"png"]; [nBar.layer setContents: (id)[UIImage imageWithContentsOfFile: barBgPath].CGImage];

the downside is the buttons are not generated off the proper tint but you can set the navbar color to whatever is closest to your bg image and the tint should be taken care of.

drunknbass