一、下面是自定义NavigationBar,可以随意放置nav的背景图,同时可以兼容iOS5和iOS4及以前的版本,主要是重写系统的nav,用到了类别。这是第一次用类别,收获不小。@implementation UINavigationBar (CustomBackground) //重写navbar
- (UIImage *)barBackground{
return [UIImage imageNamed:@"1.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];
//[[self backItem] setBackBarButtonItem:<#(UIBarButtonItem *)#>]
}
@end
二、自定义nav上面的按钮,左右各示范一个,用到了IBarButtonItem的initWithCustomView方法,设置按钮的背景图片 //返回按钮
UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 100.0, 62.0, 29.0)];
[backBtn setTitle:@"返回" forState:UIControlStateNormal];
[backBtn setBackgroundImage:[UIImage imageNamed:@"top_btn_bg.png"] forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
self.navigationItem.leftBarButtonItem=backBarBtn;
[backBtn release];
[backBarBtn release];
//首页按钮
UIButton *indexBtn = [[UIButton alloc] initWithFrame:CGRectMake(250.0, 100.0, 62.0, 29.0)];
[indexBtn setTitle:@"首页" forState:UIControlStateNormal];
[indexBtn setBackgroundImage:[UIImage imageNamed:@"back_home.png"] forState:UIControlStateNormal];
[indexBtn addTarget:self action:@selector(goIndex) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *indexBarBtn = [[UIBarButtonItem alloc] initWithCustomView:indexBtn];
self.navigationItem.rightBarButtonItem=indexBarBtn;
[indexBtn release];
[indexBarBtn release];
三、下面的方法可以为nav更换背景图片 ios5上面就不需要了,因为有了新的方法 UIImageView* imageview=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nav_bg.png"]];
imageview.frame=CGRectMake(0,0,320,44);
imageview.tag=1000;
[self.navigationController.navigationBar addSubview:imageview];
[imageview release];