UINavigationBar tint color does not update

流过昼夜 提交于 2020-12-11 10:06:49

问题


I am implementing a dark mode in my app. Here is my code (that I call when the screen is double tapped):

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()]

The only thing that updates is my status bar, but the navigation bar does update after I go into another view and return back to the main view. Why is that? Is there something I'm doing wrong?


回答1:


I was just dealing with the same issue, turns out if you change appearance() proxy at runtime it doesn't have any effect. You need to change directly the properties of instances. So what you need to do is have subclassed UINavigationBarController with method where you set the colors and status bar appearance, for instance:

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

    }
}

Then when you double tap the screen:

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



回答2:


Got it. You can't change appearance() at runtime, but you can just do navigationController?.navigationBar.tintColor = UIColor.redColor()



来源:https://stackoverflow.com/questions/32077139/uinavigationbar-tint-color-does-not-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!