Skip to main content

How to Customise Navigation Bar and Back Button In IOS

Navigation Bar

Here are what you’ll learn in this tutorial:
  • Customising the View with background image
  • Customising UINavigationBar including background image and text style of title
  • Customising the appearance of UIBarButtonItem
As usual, we’re going to illustrate the concept by converting a plain navigation bar to one with customised graphics. However, to help you focus on learning the customisation, we’ve prepared the Xcode project for you to start with. Before proceeding.

If you build and run the project, you’ll get an app with simple navigation UI. Now we’ll work together to style the navigation bar, customise the bar buttons and assign our own background image for the view.
Demo App – Custom Navigation Bar
Customising the View Background

First, we would like to change the background of view controller with our own image. If you open the Xcode project, you’ll see a set of images that we’ve added for you. To set the background image, open the “RecipeViewController.m” and add the following line of code to the end of “viewDidLoad” method:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];

Apparently, you can use the “backgroundColor” property of the view to change the background color. What you may not know is that you can also use the same property to set the background image. The trick is to create a UIColor object using the “colorWithPatternImage”. During drawing, the image in the pattern color is tiled as necessary to cover the view area.

Styling the UINavigationBar

Prior to iOS 5, developers can only change the style of navigation bar through a handful of properties. But the problem is the change only applies to the navigation bar of a specific view. From iOS 5 and onwards, the SDK allows developers to style the navigation bar by using Appearance API. You can easily customise the appearance of navigation bars throughout the app using the appearance proxy ([UINavigationBar appearance]).

Changing Navigation Bar Background

Open “AppDelegate.m” and add the following in the “application:didFinishLaunchingWithOptions” method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     UIImage *navBackgroundImage = [UIImage imageNamed:@"navbar_bg"];
     [[UINavigationBar appearance] setBackgroundImage:navBackgroundImage                                                                                             forBarMetrics:UIBarMetricsDefault];

    return YES;
}

The first line of code creates the UIImage object with our own background image of navigation bar. Then we use the appearance proxy to assign the image.

Customising the Title Text of Navigation Bar

Next, we’ll change the font style of the title text. You can customise the text style by using the “titleTextAttributes” properties of the navigation bar. You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the following text attribute keys:
  • UITextAttributeFont – Key to the font
  • UITextAttributeTextColor – Key to the text color
  • UITextAttributeTextShadowColor – Key to the text shadow color
  • UITextAttributeTextShadowOffset – Key to the offset used for the text shadow
In the “application:didFinishLaunchingWithOptions” method of AppDelegate.m, add the following code:

[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary                                      dictionaryWithObjectsAndKeys:[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], UITextAttributeTextColor,[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],UITextAttributeTextShadowColor,[NSValue valueWithUIOffset:UIOffsetMake(0, 1)],UITextAttributeTextShadowOffset,[UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:21.0], UITextAttributeFont, nil]];

The above code alters the text style of navigation bar title. We use the HelveticaNeue-CondensedBlack as the font type, set the color to white and add a shadow to the text.

Now compile and run the app again. This is what the customised navigation bar looks like:

Navigation Bar with customized background and text style

Customising the Appearance of UIBarButtonItem

Lastly, we’re going to change the appearance of back button, as well as, other navigation bar buttons (i.e. UIBarButtonItem). Again, open “AppDelegate.m” and add the following code in the “application:didFinishLaunchingWithOptions” method:

// Change the appearance of back button
UIImage *backButtonImage = [[UIImage imageNamed:@"button_back"]                                                                                              resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage                                                                                 forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

// Change the appearance of other navigation button
UIImage *barButtonImage = [[UIImage imageNamed:@"button_normal"]                                                                                            resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)];
[[UIBarButtonItem appearance] setBackgroundImage:barButtonImage                                                                                                      forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

We first create the UIImage objects using our own images (i.e. button_back.png and button_normal.png) and then set the image object as the background image of the UIBarButtonItem. But what’s the resizableImageWithCapInsets: method for? The buttons in navigation bar are not in fixed size. It’ll be automatically resized depending on the text length of the button. For round rectangular button, you probably don’t want to stretch the button in all directions. So we use the resizableImageWithCapInsets: method to add cap insets to the image. During resizing of the image, areas covered by a cap are not resized. The below illustration will give you a better idea about the cap inset.

resizableImageWithCapInsets illustrated

We define the cap inset using the UIEdgeInset structure. The UIEdgeInsets is structure that specifies float values for each cap inset: top, left, bottom and right areas of an image. For instance, line 1 of the above code instructs iOS that the left 13 pixels and the right 6 pixels of the back button image are not scaled or resized.

After making the code change, compile and run the app again. You should now have the custom back and edit buttons.

Navigation Bar with customised UIBarButtonItems


Comments

Post a Comment

Thank You.

Popular Posts

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...