ios之自定义UINavigationBar
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!