Skip to main content

UINavigationBar: How to customize Navigation Bar

By customization we can change look and feel of Navigation Bar. Below is sample code which demonstrates how to customize Navigation Bar.

We can achieve this by using Categories in Objective-C:

Code Sample:

/*********************************************************/
@interface UINavigationBar (CustomNavBarImage)
 - (void) setNavBackgroundImage:(UIImage*)bgImage;
 - (void) removeNavBackgroundImage ;
@end

/************************************************************/

//.m file (Implementaion file)
#import "UINavigationBar+CustomNavBarImage.h"

@implementation UINavigationBar (CustomNavBarImage)

- (void) setNavBackgroundImage:(UIImage*)bgImage
{
 if (bgImage == NULL)
 return;
UIImageView *myImageView= [[UIImageView alloc] initWithImage:bgImage];
myImageView.frame = CGRectMake(0,0,320,44);
[self addSubview:myImageView];
[myImageView release];
// If You want to add some buttons and title go through that
//[myImageView release];
UIButton *addButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];//UIButtonTypeCustom
addButton .frame = CGRectMake(10, 0, 100, 44);
[addButton setTitle:@"Add" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(clickOnAddButton:) forControlEvents:UIControlEventTouchUpInside];
//Font size of title
addButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
[myImageView addSubview:addButton];
myImageView.userInteractionEnable = YES;
}

- (void) removeNavBackgroundImage
{
NSArray *subviewsArray = [self subviews];
for (int i=0; i<[subviewsArray count]; i++)
{
if ([[subviewsArray objectAtIndex:i]  isMemberOfClass:[UIImageView class]])
{
[[subviewsArray objectAtIndex:i] removeFromSuperview];
}
}
}

@end

// Calling

// Set Navigation Bar Image
[[self.navigationController navigationBar] performSelectorInBackground:@selector(setNavBackgroundImage:) withObject:bgImage];

// Remove Image
[[self.navigationController navigationBar] performSelector:@selector(removeNavBackgroundImage) withObject:nil];

// Second Simple Way : (Without Categories)

// Set  first this : self.NavigationController.navigationBarHidden = YES;

-(void) setCustomNavBar
{
UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake (0,0,320,44)];
// set your background image name like NavBarImage.png
myImage.image = [UIImage imageNamed:@"yourBGImage"];
myImage.backgroundColor = [UIColor clearColor];
[self.view addSubview: myImage];
UIButton *addButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];//UIButtonTypeCustom
addButton .frame = CGRectMake(10, 0, 100, 44);
[addButton setTitle:@"Add" forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(clickOnAddButton:) forControlEvents:UIControlEventTouchUpInside];
//Font size of title
addButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
[myImage addSubview:addButton];

myImage.userInteractionEnable = YES;
}

//Called this function on viewdidload or loadView or viewWillAppear (according to your preference).

[self performSelector:@selector(setCustomNavBar)];

Other Methods are :

Until iOS 5 came out, we used drawRect override in AppDelegate to customize UINavigationBar.
Now iOS 5 give us some new method for styling (and old doesn’t work).

How to build app that will work on iOS 4 and iOS 5 with stylized UINavigationBar?

You must to do both!

In AppDelegate use this code:

@implementation UINavigationBar (UINavigationBarCategory)
- (void)drawRect:(CGRect)rect {
       UIImage *img = [UIImage imageNamed:@"navbar.png"];
       [img drawInRect:rect];
}
@end


and in
viewDidLoad method for iOS5 (in your view implementation):

if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
   [self.navigationController.navigationBar setBackgroundImage:[UIImage  imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
}


If you see, here we are asking if navbar will respondToSelector to avoid crash on iOS4!
If you use this for iOS5:

if([[UINavigationBar appearance] respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];
}



Your app will not work on iOS4 because can’t found [UINavigationBar appearance].
But, if you want to target only iOS5 this snippet will work for whole app. You can put it just in didFinishLaunchingWithOptions method in AppDelegate:

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg.png"] forBarMetrics:UIBarMetricsDefault];

Comments

Popular posts from this blog

WPF-MVVM: RelayCommand Implementation

In WPF if we are implementing MVVM pattern then we need to play with Command rather than Events. You can use ICommand interface to create each command class. Implementation of ICommand in a class gives you CanExecute(), Execute() methods which take part in the action performed by Command.   Rather than making Command Class for each Command we can implement a generic Relay Command to get Command. Below is a RelayCommand class that we will implement.   ///   <summary>      ///  To register commands in MMVM pattern      ///   </summary>      class   RelayCommands  :  ICommand     {          readonly   Action < object > _execute;          readonly   Predicate < object > _canExecute;  ...

iOS Dev: Encryption in Objective-C

Hello Friends: In this Article/Post, I introduced the one encryption technique in Objective-C.  Encryption Component Features in all  Symmetric Encryption: AES, Blowfish, Twofish, RC2, ARC4, DES, 3DES, PBES1, PBES2. Hash Algorithms :  SHA-1 , SHA256, SHA384, SHA512, MD2, MD4, MD5, HAVAL. Hash Algorithms: RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320. Encoding: Base64, hex, quoted-printable,  URL-encoding . HMAC with any supported hash algorithm: HMAC-MD5,  HMAC-SHA1 , etc. Password-based Key Derivation Functions: PBKDF1, PBKDF2 PKCS7 -- P7S and P7M creation, decryption, verification. Public key encryption/decryption with digital certificates. Digital signature creation/verification with digital certificates. Bzip2 in-memory compression. Encrypt / decrypt strings or byte data. Return encrypted data as Base64, quoted-printable, or hex-encoded strings. Hash strings or binary data using SHA1, MD2, MD5, HAVAL, SHA384, or SHA512. Public-key encryp...

iPhonegap: Developing a PhoneGap Application

Tutorial: Developing a PhoneGap Application Reference :  Here In this tutorial, you create a fully functional employee directory application with  PhoneGap . You will learn: How to use different local data storage strategies. How to use several PhoneGap APIs such as Geolocation, Contacts, and Camera. How to handle specific mobile problems such as touch events, scrolling, styling, page transitions, etc. How to build an application using a single page architecture and HTML templates. How to build (compile and package) an application for 6 platforms using  PhoneGap Build . To complete this tutorial, all you need is a code editor, a modern browser, and a connection to the Internet. A working knowledge of HTML and JavaScript is assumed, but you don’t need to be a JavaScript guru. Setting Up Download the assets for the workshop  here . Unzip the file anywhere on your file system. If your code editor allows you to “open a directory”, open the phonegap...