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; } } @endBasically, 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.
No comments:
Post a Comment