Customizing the background of an UINavigationBar
To customize the background image of the navigation bar, you can create a separate class extending UINavigationBar and override its drawRect method.
To do that, first create a new class named STNavigationBar with the following definition in the STNavigationBar.h file:
@interface STNavigationBar : UINavigationBar { }
Then, implement the drawRect method in the STNavigationBar.m file:
@implementation STNavigationBar - (void)drawRect:(CGRect)rect { UIImage *barImage = [UIImage imageNamed:@"STNavigationBar.png"]; [barImage drawInRect:rect]; } @end
After creating this class, you can now use it anywhere you need a navigation bar with this particular style. In Interface Builder, specify STNavigationBar instead of UINavigationBar under Custom Class > Class.
Selecting the background image based on the current device
To support both iPhone < 4 and the Retina Display, it would be best to create two images, one for each resolution. The resolutions at which the navigation bar is rendered are:
- iPhone < 4: 320 x 44 px
- Retina Display: 640 x 88 px
To detect this, you can inspect the screen’s scale factor.
@implementation STNavigationBar - (void)drawRect:(CGRect)rect { UIImage *barImage; if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2) { barImage = [UIImage imageNamed:@"STNavigationBar88.png"]; } else { barImage = [UIImage imageNamed:@"STNavigationBar44.png"]; } [barImage drawInRect:rect]; } @end