有不同的方法可以为 ios 5 及更高版本和低于 ios 5 的 ios 设置 Uinavigationbar 背景图像
对于 ios 5,您可以在应用委托中使用以下代码
//Customize the look of the UINavBar for iOS5 devices
UIImage *gradientImage44 = [[UIImage imageNamed:@"navigationBar44"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
UIImage *gradientImage32 = [[UIImage imageNamed:@"navigationBar32"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UINavigationBar appearance] setBackgroundImage:gradientImage44
forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:gradientImage32
forBarMetrics:UIBarMetricsLandscapePhone];
但是如果您使用的任何 ios 版本低于 ios 5,您将不得不子类化 UINavigationControl 并重载 drawRect 像
@interface CustomNavigationBar : UINavigationBar
@end
@implementation CustomNavigationBar
-(void) drawRect:(CGRect)rect
{
UIImage *image = [UIImage imageNamed: @"myNavBarImage"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
// this can go anywhere
+(UINavigationController*) myCustomNavigationController
{
YOurViewController *vc = [[[YOurViewController alloc] init] autorelease];
UINavigationController *nav = [[[NSBundle mainBundle]
loadNibNamed:@"CustomNavigationController" owner:self options:nil] objectAtIndex:0];
nav.viewControllers = [NSArray arrayWithObject:vc];
return nav;
}
像这样,您可以自定义导航栏,并且对所有 ios 版本都有效。
您可以通过使用检查 ios 5
if ([[UINavigationBar class]respondsToSelector:@selector(appearance)]) {
///ios 5 and above.
}