Posterous theme by Cory Watilo

Custom nav bar / toolbar backgrounds in iOS5

iOS5 brings out this brilliant new ‘appearance’ proxy that allows us to set our toolbar/nav bar backgrounds in one place. No more writing dodgy categories that override drawrect, or inserting subviews at a magical z-order!

Put this in your app’s didFinishLaunchingWithOptions:

UIImage *barsBack = .. some 1x44px image ..

[[UIToolbar appearance] setBackgroundImage:barsBack
                        forToolbarPosition:UIToolbarPositionAny
                                barMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setBackgroundImage:barsBack
                                   forBarMetrics:UIBarMetricsDefault];

Pretty simple right?

Now if you’re in the unenviable position of writing an app that just has to work on ios4 as well, you could wrap the above block in an if (IsIos5()) { block, and use the same background-hack categories as you used to in ios4 but wrap the code in an if (IsIos4()) { block, with these handy macros:

#define IsIos5() ([[[UIDevice currentDevice] systemVersion] intValue] >= 5)
#define IsIos4() ([[[UIDevice currentDevice] systemVersion] intValue] <= 4)

Good luck!