UINavigationBar setBackgroundImage:forBarMetrics:不工作

我只是切换到iOS 5,除了自定义导航栏,一切似乎都在我的应用程序中工作。 我环顾四周,并按照每个人的build议调用新方法setBackgroundImage:forBarMetrics:但它似乎不工作。 这是我试图放置在应用程序委托和一些视图控制器的viewDidLoad方法内的代码:

UINavigationBar *nb = [[UINavigationBar alloc]init]; if( [nb respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) { UIImage *image = [UIImage imageNamed:@"navBarBackground.png"]; [nb setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; } [nb release]; 

不幸的是,这是行不通的。 如果有人有任何build议,我都耳朵!

要将image应用于所有导航栏,请使用外观代理:

 [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 

对于一个单独的酒吧:

 // Assuming "self" is a view controller pushed on to a UINavigationController stack [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; 

在你的例子中,背景图像不会改变,因为nb没有连接任何东西。

通过回答rob是正确的,但如果应用程序运行在iOS 4.3或更低的应用程序将崩溃。 所以你可以像这样实现

 if([[UINavigationBar class] respondsToSelector:@selector(appearance)]) //iOS >=5.0 { [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar.png"] forBarMetrics:UIBarMetricsDefault]; [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBar-Landscape.png"] forBarMetrics:UIBarMetricsLandscapePhone]; } 

这将设置模式风景和肖像的图像

您需要从导航控制器获取导航栏。 现在你只是创build一个,然后释放它时释放。 您需要获取您的视图控制器的导航控制器。

 UINavigationController * navigationController = [self navigationController]; UINavigationBar * nb = [navigationController navigationBar]; 

请注意,如果您想将其应用于工具栏,则略有不同。 下面是一个例子,build立在Rob的答案上:

  [[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"NavBarDarkWoodGrain.png"] forToolbarPosition:UIToolbarPositionBottom barMetrics:UIBarMetricsDefault]; 

你没有做像使用UINavigationBar子类的东西? 如果你这样做,并重写drawRect:在iOS5和以上,事情将中断。

在这里看到我的答案,以支持两种操作系统版本。

这对我有效。

 UIView *parentViewLeft = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; parentViewLeft.backgroundColor = [UIColor clearColor]; if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) { [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault]; } else { UIImageView* imgBG = [[UIImageView alloc]init]; imgBG.image = [UIImage imageNamed:@"navbar.png"]; imgBG.frame = CGRectMake(-10,0, 330, 44); [parentViewLeft addSubview:imgBG]; } UIBarButtonItem *customBarButtomLeft = [[UIBarButtonItem alloc] initWithCustomView:parentViewLeft]; self.navigationItem.leftBarButtonItem = customBarButtomLeft;