I would like to set an image background to the navigation bar on my iphone app. Most solutions suggest using drawRect in a c开发者_如何学Goategory like:
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
However, Apple does not recommend this. Any other suggestion?
Thx for helping,
Stephane
Apple strongly advise us to use subclasses rather than categories (WWDC 2011, Session 123).
Create a subclass which implements the drawRect:
method and set the class of your navigation bar to your custom class:
- if you're working in Interface Builder, change the class in the inspector
- if you create a stand-alone navigation bar (without nav controller), instantiate your custom class
- if you create a navigation controller programmatically, you could take advantage of the ObjC runtime.
Class switch at runtime:
#import <objc/runtime.h>
...
object_setClass(theNavController.navigationBar, [CustomNavigationBar class]);
You should also avoid using [UIImage imageNamed:...]
each time in drawRect:
as it might have an impact on performance (for animations). Cache it in an ivar:
if (!bgImage) {
bgImage = [[UIImage imageNamed:@"NavigationBar.png"] retain];
}
[bgImage drawInRect:...];
(and release it in dealloc)
Note: As iOS 5 is still under NDA, I can't mention how you could easily add a background image. Check out the docs for UINavigationBar.
Tested Code : 100 % works
in ur ViewDidLoad
UIImageView *iv=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"urNavBarImage.png"]];
self.navigationItem.titleView = iv;
[iv release];
NOTE:urNavBarImage should be exact size of Navigation Bar. Like this u can change every Viewcontroller Navigation bar.
I have created a custom category for UINavigationBar as follows
UINavigationBar+CustomImage.h
#import <UIKit/UIKit.h>
@interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
- (void) removeIfImage:(id)sender;
@end
UINavigationBar+CustomImage.m
#import "UINavigationBar+CustomImage.h"
@implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(110,5,100,30);
[self addSubview:imageView];
[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
I invoke it from my UINavigationController
[[navController navigationBar] performSelectorInBackground:@selector(setBackgroundImage:) withObject:image];
精彩评论