UINavigationBar 色调颜色不更新

UINavigationBar tint color does not update

我正在我的应用中实现深色模式。这是我的代码(我在双击屏幕时调用):

if darkMode == false {
UINavigationBar.appearance().tintColor = UIColor(hexString: "#3A3A3A")
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
} else {
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
UINavigationBar.appearance().barTintColor = UIColor(hexString: "#FFFDF3")
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]

唯一更新的是我的状态栏,但在我进入另一个视图并 return 返回主视图后,导航栏确实会更新。这是为什么?我做错了什么吗?

我刚刚处理了同样的问题,事实证明,如果您在运行时更改 appearance() 代理,它不会有任何效果。您需要直接更改实例的属性。因此,您需要做的是使用设置颜色和状态栏外观的方法对 UINavigationBarController 进行子类化,例如:

class ColorNavigationController: UINavigationController {

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        setupForColor(UIFactory.sharedInstance.tintColor) //provides default color
    }

    func setupForColor(color: UIColor) {
        navigationBar.tintColor = color
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()]
        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent

    }
}

然后当您双击屏幕时:

if let colorNavigationController = self.navigationController as? ColorNavigationController {
    colorNavigationController.setupForColor(UIColor.redColor) // based on your current scheme
}

知道了。您不能在运行时更改 appearance(),但您可以只执行 navigationController?.navigationBar.tintColor = UIColor.redColor()