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

5

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

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

在AppDelegate中,然而,在这种情况下,这不起作用因为它需要动态完成。
我还尝试了navigationController?.navigationBar.barTintColor = UIColor.white,但这也不起作用。
更新:
我认为很多回答都误解了这个问题的目的 - 这与刚发布的iOS13暗模式没有任何关系 - 这是我想要添加到我的应用程序中的一个独立的暗模式功能(类似于其他应用程序,如Messenger等,在iOS 13发布之前在应用内提供暗模式)。我需要做的是在UINavigationBar已经显示在屏幕上后动态更新其颜色,就像我可以通过执行view.backgroundColor = .white来更改视图的背景颜色,并且这将实时更新屏幕上的颜色。

你可以查看以下链接了解iOS13中UINavigationBar的更改: https://sarunw.com/posts/uinavigationbar-changes-in-ios13.html - byaruhaf
2个回答

1

通过将导航栏设置为半透明 (在 AppDelegate 中实现):

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

接下来我创建一个视图,并将其放置在导航栏后面,代码如下(使用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))
}

其中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)
    }
}

最终,为了更新颜色,我进行了如下设置。
coverView.backgroundColor = universalWhite() 

where

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

0

您可能希望查看UIViewController提供的特性来确定当前的界面样式,而不是手动检查运行iOS 13+的版本。使用此方法,您可以为两种外观在Assets文件夹中定义颜色。

对于iOS 13以下的版本,您可以使用类似@byaruah所述的方法,但这不是全局效果。您还应考虑使用UINavigationBar.appearance()功能进行全局处理。


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