Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - NavigationBar Custom Background [duplicate]

Possible Duplicate:
How to add background image on iphone Navigation bar?

I am looking for a way to have a custom navigation bar and need to have a custom navigation bar background to achieve this. I was looking around for how to do this, but could not find a solution. If anyone has the solution, help is much appreciated.

like image 674
intl Avatar asked Feb 14 '10 02:02

intl


3 Answers

Since iOS5, you can easily set a custom background, with the method setBackgroundImage:forBarMetrics: But you must check if the user's phone has the right OS.

if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"texture.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
}

This is a nicer solution, cause it's in the doc.

like image 84
Martin Avatar answered Sep 24 '22 15:09

Martin


(supplemental to Andrew Johnson's response)

The linked Apple.com post includes 3 or 4 different solutions, most of which only "half" work. I think the most elegant/effective of them is this one:

@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

HOWEVER ... it's not good-practice ObjC to od that as a category (should be an override), and it has some problems of its own.

So, a more general and powerful solution is here:

http://samsoff.es/posts/customize-uikit-with-method-swizzling

like image 28
Adam Avatar answered Sep 22 '22 15:09

Adam


You can just add a subview (a UIImageView) to the navaigationBar, which is just a UIView subclass.

UINavigationBar nb = [[UINavigationBar alloc]init];
[nb addSubview: foo];
[nb release];

Here's a forum post that describes how to wrap this up into a category: http://discussions.apple.com/thread.jspa?threadID=1649012&tstart=0

like image 32
Andrew Johnson Avatar answered Sep 22 '22 15:09

Andrew Johnson