///////////////////////////////////////////////////////////////// 2012.2.24更新 (iOS 4 & iOS 5 均适用)
- - (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
更详细的解决方法请参考:
http://stackoverflow.com/questions/7657465/uinavigationbars-drawrect-is-not-called-in-ios-5-0
///////////////////////////////////////////////////////////////// iOS 5之前的解决方法,在iOS 5中已经不再适用
在iPhone开发中, 有时候我们想给导航条添加背景图片, 实现多样化的导航条效果, 用其他方法往往无法达到理想的效果, 经过网上搜索及多次实验, 确定如下最佳实现方案:
为UINavigatonBar增加如下Category:
- @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
例如, 在我的项目中, 添加如下代码:
- /////////////////////////////////////////////////////////
- /* input: The image and a tag to later identify the view */
- @implementation UINavigationBar (CustomImage)
- - (void)drawRect:(CGRect)rect {
- UIImage *image = [UIImage imageNamed: @"title_bg.png"];
- [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
- }
- @end
- /////////////////////////////////////////////////////////
- @implementation FriendsPageViewController
- // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- - (void)viewDidLoad {
- self.navigationBar.tintColor = [UIColor purpleColor];
- [self initWithRootViewController:[[RegPageViewController alloc] init]];
- [super viewDidLoad];
- }
- ......
实现的效果如下图: