将NavigationBar手动切换到黑暗模式

问题描述 投票:0回答:1

在我的应用中,我有一个手动开关可以在亮/暗模式之间切换,而我要完成的工作是使导航栏在以下情况下触发“暗模式”外观(白色文本/图标和黑色背景)我需要在明暗之间切换。

我已经尝试了以下所有内容:

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

self.navigationController?.navigationBar.barTintColor=UIColor.white
self.navigationController?.navigationBar.titleTextAttributes=[NSAttributedString.Key.foregroundColor:UIColor.white]

并且输入上面尝试的任何代码时,导航栏都不会改变。

完成此操作的正确方法是什么?

swift uinavigationbar ios-darkmode
1个回答
0
投票

无法通过一条简单的线将条形更改为您自己的局部暗模式。但是我们可以编写一个功能,执行与您想要的功能类似的功能。请注意,执行此操作的正确方法是在条形样式和颜色上添加开关,这些开关使用特征收集在不同的全局视觉模式之间进行更改。

extension UIViewController {

    enum NavigationBarStyle {
        case dark, light
    }

    func setNavigationBar(style: NavigationBarStyle) {

        guard let bar = view.subviews.first(where: { return $0 is UINavigationBar }) as? UINavigationBar else { return }

        func set(item: UINavigationItem, color: UIColor) {
            item.rightBarButtonItem?.tintColor = color
            item.leftBarButtonItem?.tintColor = color
        }

        bar.barStyle = style == .dark ? .black : default

        let color: UIColor = style == .dark ? .white : .black
        for item in bar.items ?? [] {
            bar.titleTextAttributes = [.foregroundColor: color]
            set(item: item, color: color)
        }

    }

}

您需要确保已将导航栏添加到控制器的子视图。我通过编程方式做了类似的事情,但是我想使用界面生成器是一样的。

let navbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 375, height: 45))

navbar.backgroundColor = UIColor.white
navbar.delegate = self

let navItem = UINavigationItem()
navItem.title = "Title"
navItem.leftBarButtonItem = UIBarButtonItem(title: "Left", style: .plain, target: self, action: nil)
navItem.rightBarButtonItem = UIBarButtonItem(title: "Right", style: .plain, target: self, action: nil)

navbar.setItems([navItem], animated: true)

view.addSubview(navbar)

然后,最后,在进行一些操作或您喜欢的任何操作后设置样式。使用;

setNavigationBar(style: .dark)
© www.soinside.com 2019 - 2024. All rights reserved.