Customised UINavigationBar background in iOS 4 and 5
Recently I came across the situation that I needed to support a custom background for a UINavigationBar in an app that had to work for both iOS 4 and iOS 5. After some Googling I came up with this approach.
First the easy one, iOS 5;
[sourcecode language="objc"]
if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
[self.navigationController.navigationBar setBackgroundImage:navigationBackgroundImage forBarMetrics:UIBarMetricsDefault];
}
[/sourcecode]
Note the test on the navigation bar class to check if it supports the UI proxy extensions. This must be done in iOS 4 otherwise a crash will result.
Now for iOS 4 we have to create a category, fortunately this is very simple;
[sourcecode language="objc"]
@implementation UINavigationBar (CustomBackground)
- (void)drawRect:(CGRect)rect
{
UIImage *navBackgroundImage = [[UIImage imageNamed:@"navigation-background"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0];
[navBackgroundImage drawInRect:rect];
}
@end
[/sourcecode]
The drawRect:
method is not called in iOS 5 so it is safe to leave this category in your app. Just as a small side note, Apple has deprecated strechableImageLeftCapWidth:topCapHeight:
in iOS 5 in favour of resizableImageWithCapInsets:
.