【问题标题】:Set the navigation bar and status bar with different colors设置不同颜色的导航栏和状态栏
【发布时间】:2016-06-29 19:39:37
【问题描述】:

我正在使用 Swift 制作一个应用,我希望状态栏和导航栏具有不同的颜色,例如 iOS 上的谷歌翻译应用或谷歌音乐应用。

我已经知道状态栏和导航栏的颜色不能单独设置,但是有什么技巧可以做到吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow!这个问题的信息有点少。你能分享一下你尝试过的,你遇到了什么问题吗?
  • @JayBlanchard 问题是我希望状态栏和导航栏具有不同的颜色,但在 iOS 中默认情况下它们共享相同的颜色。但就像我之前所说的,有些应用程序有不同的颜色。

标签: ios swift


【解决方案1】:

一个简单的方法是在导航栏顶部添加一个与状态栏大小完全相同的视图。

例如,要使状态栏变为红色,您可以在 viewDidLoad 方法中添加以下内容:

let statusBarHeight = CGFloat(20)
let colorView = UIView(frame: CGRectMake(0, -statusBarHeight, self.view.bounds.width, statusBarHeight))
colorView.backgroundColor = UIColor.redColor()
self.navigationController?.navigationBar.addSubview(colorView)

【讨论】:

  • 只是想澄清一下,有没有人这样做并在 App Store 上获得了该应用程序?我想在我当前的应用程序中使用它,但担心 Apple 的指导方针。
  • 是的,这并没有违反 Apple 的指导方针。您只是在导航栏中添加一个视图,这非常好。
【解决方案2】:

https://gist.github.com/wh1pch81n/ef921944f732de1c45bb93646b462d6f

您可以获得对状态栏的引用。然后更改背景颜色属性。

UIView *subViewWindow = [[UIApplication sharedApplication] valueForKey:@"statusBarWindow"];
((UIView *)subViewWindow[0]).backgroundColor = UIColor.redColor;

【讨论】:

    【解决方案3】:

    UINavigationBar 的setBackgroundImage:forBarMetrics: 是一个很好的解决方案。我在我的 obj-C 应用程序中使用了这种方法,它很好地解决了类似的问题。对于纯背景色,我制作了一个像素宽的单色图像。

    【讨论】: