Monday, May 9, 2011

Put background image in navigation bar in iphone sdk

Hello friends,

Today I am going to write one useful method for making custom navigation bar. We will change the color of navigation bar by inserting color image in navigation bar. We can do this by making new class for the custom navigation controller. Make following two files in any application.
  • Create Objective-C class file. Do not create xib. In the header file insert following code. Import the <UIKit/UIKit.h> file.
@interface UINavigationBar
    - (void) setBackgroundImage:(UIImage*)image;
    - (void) clearBackgroundImage;
@end

  • Then in implementation file write the following code.
@implementation UINavigationBar (CustomImage)

- (void) setBackgroundImage:(UIImage*)image {
    if (image == NULL) return;
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 0, 320, 44);
    [self insertSubview:imageView atIndex:0];
    [imageView release];
}

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

@end
  • Now write the following code in the application where you want the custom navigation bar. Generally we write such code in viewWillAppear method.
UINavigationBar *navBar = self.navigationController.navigationBar;
UIImage *image = [UIImage imageNamed:@"NavigaionBarBackground.png"];
[navBar clearBackgroundImage]; 
[navBar setBackgroundImage:image];

No comments:

Post a Comment