繁体   English   中英

iOS 13:使用 UINavigationBarAppearance 时忽略 NavigationBar BarStyle

[英]iOS 13: NavigationBar BarStyle is ignored when using UINavigationBarAppearance

我有一个自定义颜色的导航栏,我需要确保状态栏颜色设置为白色。 在 iOS 13 之前,这很容易做到,这是来自 UIViewController 的代码片段,它做得很好:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.barStyle = .black
}

我面对 iOS 13 的问题是,我现在需要使用 NavigationBar 的 standardAppearance 和 scrollEdgeAppearance 来取消新 UIKit 中的强制背景透明度。虽然我能够将 NavigationBar 的文本和背景颜色设置为我想要的需要 UINavigationBarAppearance() 它将我的状态栏颜色恢复为黑色。 这是一个重现该问题的简单示例:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.standardAppearance = UINavigationBarAppearance() // <--- This is the line that reverts my status bar colour back to black
    self.navigationController?.navigationBar.barStyle = .black
}

我不确定这是我做错了什么还是 UIKit 错误?

编辑

最后通过将以下两个属性添加到我的 Info.plist 文件中设法解决了这个问题:

<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>

Info.plist 属性

我学得很辛苦,但是,

“仅仅创建UINavigationBarAppearance的实例是不够的。”你必须在 UINavigationBar 实例上实际设置它。

这实际上不是我说的,我在堆栈上的一个线程上发现了这个,我正在寻找它,但无法为你找到它。 但是,在上下文中应该对您有所帮助的内容如下。

 //Using this we have to first set up the appearance.

 UINavigationBarAppearance *appearance = [UINavigationBarAppearance new];
 appearance.titleTextAttributes = @{NSFontAttributeName: font};

 //Then u have to use it on the navigation bar and if needed on scroll Edge 

  yourNavigationBar.standardAppearance = appearance;
  yourNavigationBar.scrollEdgeAppearance = appearance; 

 if you want this globally in your navigation bars 

 UINavigationBar.appearance.standardAppearance = appearance;

另一个“hack”是在 Appdelegate 中添加它,它适用于您应用程序中的所有导航栏。

Appdelgate

func configureGlobalUI() {

UINavigationBar.appearance().barTintColor = .red
}

didFinishLaunching中调用它

我最终设法将整个应用程序的状态栏样式设置为白色。 There are many solutions on SO but from my experience some of them can be very iOS specific, ie something that worked for someone on iOS 8-12 doesn't necessary mean it will work on iOS 13 with XCode 11 .

这是我的解决方案,适用于iOS 13XCode 11 (也在运行iOS 12的设备上进行了测试,以实现向后兼容性)和UINavigance . 在 Info.plist 文件中添加以下两个属性:

Info.plist 属性

<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>

如果不将UIViewControllerBasedStatusBarAppearance设置为false ,是否有解决方案? 我想更改每个视图 controller 的状态栏颜色。

暗模式的更改包括名为 overrideUserInterfaceStyle 的新 UIView 和 UIViewController 属性。 这是表明您想要特定的浅色/深色样式而不是我们响应当前深色模式 state 的默认行为的首选方式。

如果您在导航栏或导航 controller 上设置此项,那么您应该会得到您期望的行为(假设您希望到处都是亮或暗)。 如果您需要更多控制,那么将 UINavigationController 子类化以更改其行为可能更有意义(例如,通过覆盖 -childViewControllerForStatusBarStyle 并返回顶部视图 controller)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM