ios5 自定义导航条问题
在ios5之前的系统中,可以通过定义导航条类别的方式自定义导航条:
@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
// Drawing code
UIImage *image = [[UIImage imageNamed:@"header.png"] retain];
[image drawInRect:CGRectMake(0, 0,self.frame.size.width , self.frame.size.height)];
[image release];
}
@end
但在ios5中,这种方式不起作用了。详见ios 5.0发布说明:
在iOS 5中,UINavigationBar, UIToolbar, and UITabBar 的实现方式改变了,因此drawRect:方法不会被调用了。除非在他们的子类中实现。
|
因此,要在iOS 5.0中继续使用自定义的导航条,这里提供两种方法:
1、使用5.0中新提供的UINavigationBar的方法setBackgroundImage:forBarMetrics:来设置背景。
但是为了与4.0等系统兼容,在使用该方法前必须先进行判断:(在5.0之前的系统中继续使用原来的方法)
(需要在每个用到navigationbar的地方都调用该方法,可能改动的地方比较多)
1 UINavigationBar *navBar = [myNavController navigationBar];
2 if ([navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
3 {
4 // set globablly for all UINavBars
5 [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"brnlthr_nav.jpg"] forBarMetrics:UIBarMetricsDefault];
6 // ...
2、使用UINavigationBar的子类的方式来实现:(用这种方式可以不用对每个使用navigationbar的地方都进行修改,属于懒人做法)
@interface MyNavigationBar : UINavigationBar
@end
@implementation MyNavigationBar
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
}
@end
@implementation UINavigationBar (LazyNavigationBar)
+ (Class)class {
return NSClassFromString(@"MyNavigationBar");
}
-(void)drawRect:(CGRect)rect {
UIImage *backImage = [UIImage imageNamed:@"backNav.png"];
[backImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
3.使用category 范畴 来实现
@implementationUINavigationBar(MyCustomNavBar)
-(void)setBackgroudImage:(UIImage*)image
{
CGSize imageSize =[image size];
self.frame =CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width, imageSize.height);
UIImageView*backgroundImage =[[UIImageView alloc] initWithImage:image];
backgroundImage.frame =self.bounds;
[self addSubview:backgroundImage];
[backgroundImage release];
}
@end
//The above swizzling will allow you to set any custom background image for the UINavigationBar(iOS5 & iOS4).
Here's a less-ugly solution that works for both iOS4 and 5:
@implementationUINavigationBar(CustomBackground)
-(UIImage*)barBackground
{
return[UIImage imageNamed:@"top-navigation-bar.png"];
}
-(void)didMoveToSuperview
{
//iOS5 only
if([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
{
[self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];
}
}
//this doesn't work on iOS5 but is needed for iOS4 and earlier
-(void)drawRect:(CGRect)rect
{
//draw image
[[self barBackground] drawInRect:rect];
}
@end