Dec
19
2011

Customizing UINavigationbar

Before IOS 5.0, UINavigationbar can be customized by using ‘Category’. On IOS 5.0 onwards, customizing with ‘category’ doesn’t work anymore, instead we can use a new API called:

- (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics

custom-uinavigationbar

In order to customize UINavagationBar for both IOS 5.0 and below IOS 5.0 devices, we have to prepare these two methods:

  • 1. Write a category for UINavigationBar (for IOS 4.3 and below)
  • 2. Check if device is IOS 5.0 and above, use – (void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics

To create a category, create a new file name ‘CustomNavigationBar’.
In ‘CustomNavigationBar.h’,

@interface CustomNavigationBar : UINavigationBar
@end

In ‘CustomNavigationBar.m’, draw the navigation bar with your custom image,

#import "CustomNavigationBar.h"
 
@implementation UINavigationBar (UINavigationBarCategory)
 
- (void)drawRect:(CGRect)rect {
    UIColor *color = [UIColor darkGrayColor];
    UIImage *img  = [UIImage imageNamed: @"img-bgtopbar.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.tintColor = color;
}
@end

To replace the default Navigation bar, just #import ‘CustomNavigationBar.h’ in any classes that need to be customized.

To determine the IOS version, check like this:

float deviceVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (deviceVersion >= 5.0)
  [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img-bgtopbar.png"] forBarMetrics:UIBarMetricsDefault];

The code above check if the device version is equal to or more than IOS 5.0, if so, use the ‘setBackgroundImage’ API. With these 2 methods, you can customize the UINavigationBar for IOS 4.3 and below as well as IOS 5.0

About the Author:

Cayden is a programmer that expertize in ios and PHP development.

1 Comment + Add Comment

Leave a comment

Ads

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Facebook Page

Categories