如何为UINavigationBar设置背景图片

本文介绍了一种在iOS应用中自定义UINavigationBar背景图片的方法,并提供了适用于iOS4及更高版本的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///////////////////////////////////////////////////////////////// 2012.2.24更新 (iOS 4 & iOS 5 均适用)

[cpp]   view plain copy
  1. - (UIImage *)barBackground  
  2. {  
  3.     return [UIImage imageNamed:@"top-navigation-bar.png"];  
  4. }  
  5.   
  6. - (void)didMoveToSuperview  
  7. {  
  8.     //iOS5 only  
  9.     if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])  
  10.     {  
  11.         [self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];  
  12.     }  
  13. }  
  14.   
  15. //this doesn't work on iOS5 but is needed for iOS4 and earlier  
  16. - (void)drawRect:(CGRect)rect  
  17. {  
  18.     //draw image  
  19.     [[self barBackground] drawInRect:rect];  
  20. }  
  21.   
  22. @end  


更详细的解决方法请参考:
http://stackoverflow.com/questions/7657465/uinavigationbars-drawrect-is-not-called-in-ios-5-0


///////////////////////////////////////////////////////////////// iOS 5之前的解决方法,在iOS 5中已经不再适用

在iPhone开发中, 有时候我们想给导航条添加背景图片, 实现多样化的导航条效果, 用其他方法往往无法达到理想的效果, 经过网上搜索及多次实验, 确定如下最佳实现方案:

 

为UINavigatonBar增加如下Category:

[cpp]   view plain copy
  1. @implementation UINavigationBar (CustomImage)  
  2. - (void)drawRect:(CGRect)rect {  
  3.     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];  
  4.     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  
  5. }  
  6. @end  
 

 

例如, 在我的项目中, 添加如下代码:

 

[cpp]   view plain copy
  1. /////////////////////////////////////////////////////////  
  2. /* input: The image and a tag to later identify the view */  
  3. @implementation UINavigationBar (CustomImage)  
  4. - (void)drawRect:(CGRect)rect {  
  5.     UIImage *image = [UIImage imageNamed: @"title_bg.png"];  
  6.     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  
  7. }  
  8. @end  
  9. /////////////////////////////////////////////////////////  
  10. @implementation FriendsPageViewController  
  11. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  12. - (void)viewDidLoad {     
  13.     self.navigationBar.tintColor = [UIColor purpleColor];  
  14.       
  15.     [self initWithRootViewController:[[RegPageViewController alloc] init]];  
  16.     [super viewDidLoad];  
  17. }  
  18. ......  
 

 

实现的效果如下图:

 

带有背景图片的导航条


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值