首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >自定义UINavigationBar背景

自定义UINavigationBar背景
EN

Stack Overflow用户
提问于 2009-04-01 08:20:40
回答 14查看 52.9K关注 0票数 50

我一直在尝试为我的整个NavigationBar (不仅仅是titleView)设置一个自定义背景,但一直在努力。

我找到了这个帖子

http://discussions.apple.com/thread.jspa?threadID=1649012&tstart=0

但是我不确定如何实现给定的代码片段。代码是作为一个新类实现的吗?另外,我应该在哪里实例化UINavigationController,因为我有一个使用NavigationView模板构建的应用程序,所以根据示例,它不会在根控制器中完成

EN

回答 14

Stack Overflow用户

回答已采纳

发布于 2010-04-27 17:55:59

你只需要像这样重载drawRect:

代码语言:javascript
复制
@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
票数 29
EN

Stack Overflow用户

发布于 2011-08-06 00:15:20

乌达夫和勒夫洛是对的。这段代码运行得很好:

代码语言:javascript
复制
@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
{
  MyViewController *vc = [[[MyViewController alloc] init] autorelease];
  UINavigationController *nav = [[[NSBundle mainBundle] loadNibNamed:@"CustomNavigationController" owner:self options:nil] objectAtIndex:0];
  nav.viewControllers = [NSArray arrayWithObject:vc];
  return nav;
}

您必须创建CustomNavigationController.xib并在其中放置一个UINavigationController,然后将navigationBar类更改为"CustomNavigationBar“。

票数 44
EN

Stack Overflow用户

发布于 2011-10-19 23:08:14

在iOS 5.xx中,必须使用“外观”代理来更改控件的背景和其他样式属性,如UINavigationBarUIToolBar等。但是,这些都不适用于iOS 4.xx,因此为了向后兼容,您需要一个混合解决方案。

如果你想同时支持iOS 4.xx和iOS 5.xx设备(即你的DeploymentTarget是4.xx),你必须小心包装对外观代理的调用,在运行时检查‘外观’选择器是否存在。

您可以通过以下方式执行此操作:

代码语言:javascript
复制
//Customize the look of the UINavBar for iOS5 devices
if ([[UINavigationBar class]respondsToSelector:@selector(appearance)]) {
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBar.png"] forBarMetrics:UIBarMetricsDefault];
}

您还应该保留您可能已经实现的iOS 4.xx解决方案。如果您已经为iOS 4.xx设备实现了drawRect解决方法,如@ludwigschubert所述,您应该将其留在:

代码语言:javascript
复制
@implementation UINavigationBar (BackgroundImage)
//This overridden implementation will patch up the NavBar with a custom Image instead of the title
- (void)drawRect:(CGRect)rect {
     UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];
     [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

这将使NavBar在iOS 4和iOS 5设备上看起来都是一样的。

票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/704558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档