简体   繁体   中英

How do I customize the navigation bar on the iPhone in Xcode ?

I have the following code-snippets :

1.)

[[UINavigationBar appearance] setBackgroundImage:myImage forBarMetrics:UIBarMetricsDefault];

Where would I put that ?

or 2.)

@implementation UINavigationBar (BackgroundImage)
//This overridden implementation will patch up the NavBar with a custom Image instead of the title
- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

Where would I put that ?

I have tried adding a navigation bar to my viewcontroller but I don't exactly know where to put these pieces of code.

Snippet 1 is iOS 5.0 only. You'd put that somewhere before your navigation bar is created so possibly in applicationDidFinishLaunching: . Take a look here for more information:

Snippet 2 is what you used to have to do before iOS 5.0. That's a category on UINavigationBar . I've not actually seen overriding drawRect: in a category before but it does appear that it works. Just create a category within your project on UINavigationBar and add that code. So something like:

UINavigationBar+MyCategory.h :

@interface UINavigationBar (MyCategory)
- (void)drawRect:(CGRect)rect;
@end

UINavigationBar+MyCategory.m :

#import "UINavigationBar+MyCategory.h"

@implementation UINavigationBar (MyCategory)
- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM