Cocoa-Matic

iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Wednesday, January 12, 2011

Replace UINavigationBar background with image

Sometimes you want to show off some creativity in your apps. One of the easiest ways to do that is by changing the look of the UINavigationBar. Modifying the color is one way and is a trivial task in Interface Builder. What about replacing it entirely with an image? Turns out that's not too difficult either. Here's how...

We're going to use Categories. What are Categories?
From CocoaDevCentral.com: Categories are one of the most useful features of Objective-C. Essentially, a category allows you to add methods to an existing class without subclassing it or needing to know any of the details of how it's implemented.

This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass.



Step 1

Create a new "Objective-C class" file. I named mine: UINavigationBar-Utility.

Step 2

The header (.h) file should read as follows:
@interface UINavigationBar (Utility)

- (void)drawRect:(CGRect)rect;

@end
*The word "Utility" in parentheses can be any word you choose.

Step 3

The class (.m) file should read as follows:
@implementation UINavigationBar (Utility)

- (void)drawRect:(CGRect)rect {
     UIImage *imgPortrait = [UIImage imageNamed: @"navbar768_1.png"];
     UIImage *imgLandscape = [UIImage imageNamed: @"navbar1024_1.png"]; 
     if (imgPortrait != NULL && imgLandscape != NULL) {
          if(self.frame.size.width == 1024) {
               [imgLandscape drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
          } else {
               [imgPortrait drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
          }
     } else {
          // Draw UINavigation bar yourself
          CGContextRef context = UIGraphicsGetCurrentContext();
          UIColor *color = [UIColor blueColor];
          CGContextSetFillColor(context, CGColorGetComponents([color CGColor]));
          CGContextFillRect(context, rect);
          self.tintColor = color;
     }
}
@end
Basically, we override UINavigationBar's drawRect function. The first part attempts to set a background image, if available. (It also provides a separate image for portrait and landscape modes, which is what the nested if/else accomplishes.) If the images don't exist, we provide the else to simply color the bar blue.

So, there it is. Pretty simple to add some interesting customization to your app.

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home


« Older Entries  
Newer Entries »