From iOS 5, Apple has officially supported adding custom background image to theUINavigationBar
with setBackgroundImage:forBarMetrics:
, making such task easier than ever before.
Setting the UINavigationBar
to a custom background image can really dramatically improve your app. With the appropriate image, a custom UINavigationBar
makes the overall feeling of the app much better.
1. Set a universal background image for navigation bars of all views
- Find an appropriate custom background image for the
UINavigationBar
(Great if you have a Retina Display version.) Download the sample image of this demo if you wish. - Drag and drop the images into your project. Remember to check the option “Copy items into destination group’s folder (if needed)”.
- Goto
AppDelegate.m
and paste the code under
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
.
Remember to change “menubar.png” to the file name of your image. (as highlighted in code)
1
2
3
4
5
6
7
|
//Set the status bar to black color.
[[
UIApplication
sharedApplication
]
setStatusBarStyle
:
UIStatusBarStyleBlackOpaque
animated
:
NO
];
//Change @"menubar.png" to the file name of your image.
UIImage
*navBar = [
UIImage
imageNamed
:
@"menubar.png"
];
[[
UINavigationBar
appearance
]
setBackgroundImage
:navBar
forBarMetrics
:
UIBarMetricsDefault
];
|
Through this, you should have successfully add your custom image to everyUINavigationBar
.
2. Set the custom background image for navigation bar of a specific view
Sometimes, instead of having a universal navigation bar, you might need to set the custom background image for navigation bar of a specific view. You should do this through following steps.
- Find the appropriate image and add it to your project.
- Subclass the specific
UIViewController
for which you want to have a different navigation bar.
For example, I want to designate a certain view in the storyboard to have a different navigation bar. So I created a class calledSpecialViewController
and hooked up the view to this class. - Goto
AppDelegate.m
and paste the code under
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
1
2
3
4
5
6
|
// Rename "specialNavBar.png" to the file name of your specific navigation bar background image.
UIImage
*special = [
UIImage
imageNamed
:
@"specialNavBar.png"
];
// Rename "SpecialViewController" to the class name that you want to have a different navigation bar for.
[[
UINavigationBar
appearanceWhenContainedIn
:[SpecialViewController
class
],
nil
]
setBackgroundImage
:special
forBarMetrics:
UIBarMetricsDefault
];
|
Remember to change specialNavBar.png
to the file name of your special navigation bar background image and change SpecialViewController
to the class name that you want to have a different navigation bar for. (as highlighted in code)