动态更改 iOS 导航栏颜色(深色模式)

Alk*_*Alk 5 uiviewcontroller uinavigationcontroller uinavigationitem ios swift

我正在尝试在我的应用程序中实现暗模式切换 - 这将涉及UIViewController在屏幕上已经可见时将导航栏颜色切换为黑色。我知道如何通过设置来做到这一点

UINavigationBar.appearance().barTintColor = .black
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UINavigationBar.appearance().isTranslucent = false
Run Code Online (Sandbox Code Playgroud)

但是,在 AppDelegate 中,这在这种情况下不起作用,因为它需要动态完成。

我也试过 navigationController?.navigationBar.barTintColor = UIColor.white但这也不起作用。

更新:

我认为很多回答都与这个问题的目的混淆了 - 这与刚刚发布的 iOS13 暗模式完全无关 - 这是我想添加到我的应用程序的独立暗模式功能(类似于其他Messenger 等应用程序在 iOS 13 发布之前在应用程序内提供暗模式)。我需要做的是在 UINavigationBar 已经显示在屏幕上之后动态更新它的颜色,就像我可以通过执行更改视图的背景颜色一样,view.backgroundColor = .white这将在屏幕上实时更新颜色。

Alk*_*Alk 1

通过使导航栏半透明来实现这一点(在 中AppDelegate):

let barAppearance = UINavigationBar.appearance()
barAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: appRed]
barAppearance.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
barAppearance.shadowImage = UIImage()
barAppearance.isTranslucent = true
Run Code Online (Sandbox Code Playgroud)

接下来,我创建一个视图并将其放置在导航栏后面,如下所示(使用 SnapKit):

let coverView = UIView() 
cover.snp.makeConstraints {
        make in
        make.left.right.top.equalTo(self)
        make.bottom.equalTo(self.snp.top).offset(universalNumber(num: parent!.topbarHeight))
}
Run Code Online (Sandbox Code Playgroud)

其中 是parent我的UIViewController并且topBarHeight是:

extension UIViewController {
/**
 *  Height of status bar + navigation bar (if navigation bar exist)
 */
    var topbarHeight: CGFloat {
        return UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,更新我设置的颜色

coverView.backgroundColor = universalWhite() 
Run Code Online (Sandbox Code Playgroud)

在哪里

func universalWhite() -> UIColor {
   let defaults = UserDefaults.standard
   let darkMode = defaults.bool(forKey: "darkMode")
   if darkMode {
       return .black
   } else {
       return .white
    }
 }
Run Code Online (Sandbox Code Playgroud)