将导航栏背景设置为纯色

10

有没有办法将UINavigationController的导航栏背景设置为纯色?

我知道可以更改Tint颜色,但那样仍然会留下渐变/玻璃效果。

有没有办法消除它,并只使用纯色背景?

5个回答

47
下面的代码也会导致导航栏呈现纯色:
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor redColor]];

2
请务必设置导航栏上按钮的颜色,否则它们将无法得到颜色:[[UINavigationBar appearance] setTintColor:[UIColor redColor]]; - user486646
你在哪里做这个?我试图在带有导航栏的视图控制器的viewDidLoad中执行它,但似乎没有生效。它需要在更早的时候完成吗?我有一个故事板,它似乎覆盖了它。 - David
David,在你展示视图之前必须完成它。配置“外观”不会更新可见视图。如果您想全局设置此项,则最好在application:didFinishLaunchingWithOptions:中完成。 - Lubiluk

5

我认为您需要子类化UINavigationBar并覆盖-(void)drawRect:(CGRect)rect方法:

UIColor *colorFlat = /* any UIColor*/
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [colorFlat CGColor]);
CGContextFillRect(context, rect);

谢谢。运行得很好。为了设置按钮的颜色,我改变了导航栏的色调颜色,它们就会获得这个色调颜色。正如我所预期的那样。 - MartinHN
你知道是否可以通过外观代理来实现吗?[[UINavigationBar appearance] .....]; - MartinHN
我不知道,我在一个iOS 4.2的项目中使用了这段代码,当时外观功能还没有可用。 - Jonathan Naguin
3
重写 drawRect 在iOS7上会导致问题;它会变成 44 像素并留下一个空的 statusBar。 - Yunus Nedim Mehel

0
以下代码对我有效:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setBarTintColor:[UIColor greenColor]];
self.navigationController.navigationBar.translucent = NO;
[self.navigationController.navigationBar setShadowImage:[UIImage new]];

0

我曾经重写drawRect方法并填充颜色;但是在iOS7升级后,它会导致UINavigationBar上出现一些问题。如果你编写自己的drawrect方法,即使调用[super drawRect],它也会改变栏的尺寸,最终导致navigationBar高度为44像素。状态栏则为空。

为了获得一个纯色的navigationBar,我使用了一张图片作为背景图像(任何小的纯色图像都可以,因为你要拉伸它),并在UINavigationBar子类的initWithFrame方法中添加了这些行:

[self setBackgroundColor:[UIColor clearColor]]     
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"bgimage.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5) resizingMode:UIImageResizingModeStretch] forBarMetrics:UIBarMetricsDefault]; 

-4
创建一个扩展自UIViewControllerCustomUIViewController,并重写viewDidLoad方法,代码如下:
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0];
}

接着,在你的控制器中使用你的CustomUIViewController。

感谢


没有图片不行吗? - MartinHN
抱歉,之前的错误,请尝试使用以下代码:[UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:1.0] - kcho0
没成功。我不应该在导航栏上设置背景吗?例如 self.navigationController.navigationBar.backgroundColor?但这也不起作用 :) - MartinHN
5
如何设置导航栏背景色,而不是UIViewController的背景色。 - Alfie Hanssen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接