2012-01-13 84 views
5

我的应用程序在主页的导航栏上使用了一个导航控制器,其中包含一个图像。背景图片通过在应用委托中放置删除UINavigationBar上的背景图像

[navigationController.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault]; 
[_window addSubview:navigationController.view]; 

完成。导航栏很好地显示此图像。

其他视图将不是在导航栏中有一个图像。因此,我需要在推送任何其他视图控制器时删除此背景图像。有谁知道这可以做到吗?

在网上有很多关于添加或更改导航栏图像的答案,但这个问题有点不同。先谢谢你。

回答

3

我相信这是第一个实际的答案,这对于iOS5的,主要的问题是在背景图像的“清除”一旦你完成。那么,只需保留现有的图像,并在完成后放回原处。

@implementation MyViewController { 
    UIImage *_defaultImage; 
} 

- (void)viewWillAppear:(BOOL)animated { 
    _defaultImage = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault]; 
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar.png"] forBarMetrics:UIBarMetricsDefault]; 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    [self.navigationController.navigationBar setBackgroundImage:_defaultImage forBarMetrics:UIBarMetricsDefault]; 
} 
+0

有趣的方法! – alexshafran 2013-10-01 20:28:50

0

它看起来像要做到这一点最简单的方法是:

1)设置主页上的导航栏的阿尔法0.000001

2)把背景图像中一个UIImageView“的背后“导航栏(现在已清除)

3)使用viewWillAppear/viewWillDisappear将视图按下/弹出时,导航栏的不透明度设置为1或0.00001。

5

要删除UINavigationBar的背景的iOS 5或更高版本,你应该这样做:

[navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; 

希望它可以帮助

+1

这看起来应该可以工作,但是如果我传递真实图像,该功能只会改变任何东西。 – rgbrgb 2013-04-22 23:59:22

+0

这里一样的东西。 – 2013-05-07 10:06:31

+2

不起作用。正如rgbrgb所说。它只对某个有效图像做某些事情。 – 2013-08-14 00:16:54

3

您可以设置背景图片,在运行时创建的空白图像。

UIGraphicsBeginImageContextWithOptions(CGSizeMake(36, 36), NO, 0.0); 
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
[[UINavigationBar appearance] setBackgroundImage:blank forBarMetrics:UIBarMetricsDefault]; 

在运行时创建空白图像: How to create a blank transparent png in Objective-C?

+0

这很好。虽然我用'CGSizeZero' – 2013-10-24 16:39:03

0

这里没有什么能为我工作。搜索了几个小时后,唯一有效的工作是遵循Apple提供的source code example

我放置了下面的代码,它工作并最终从其他视图控制器中删除了导航栏图像!

// Reset everything about navigation bar. (Other flows' background image used to show up on another view controller) 
    self.navigationController!.navigationBar.setBackgroundImage(nil, for: .default) 
    self.navigationController!.navigationBar.setBackgroundImage(nil, for: .compact) 
    self.navigationController!.navigationBar.barTintColor = nil 
    self.navigationController!.toolbar.barTintColor = nil 
    self.navigationController!.toolbar.isTranslucent = true 

希望这可以帮助别人。

干杯