导航栏的色调颜色没有更新

3

我正在我的应用程序中实现暗黑模式。以下是我在双击屏幕时调用的代码:

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

只有我的状态栏更新了,但是当我进入另一个视图并返回到主视图时,导航栏确实更新了。为什么会这样?我做错了什么吗?

2个回答

1

明白了。您无法在运行时更改 appearance(),但您可以执行navigationController?.navigationBar.tintColor = UIColor.redColor()


1

我刚刚也遇到了同样的问题,结果发现如果你在运行时更改 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
}

这对我似乎不起作用。我做错了什么:func setupForColor(color: UIColor) { navigationBar.tintColor = color if darkMode == true { navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent } else { navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor()] UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } } - nintyapple
在我的深色模式转换函数中:if let colorNavigationController = self.navigationController as? ColorNavigationController { if darkMode == true { colorNavigationController.setupForColor(UIColor(hexString: "3A3A3A")!) } else { colorNavigationController.setupForColor(UIColor(hexString: "#FFF8D3")!) } } - nintyapple
你实际上也改变了 darkMode 的布尔值吗? - libec
是的,它包含在原帖的if语句中,但我认为不需要回答这个问题。(抱歉回复晚了,我的MacBook出了点问题 :/) - nintyapple
代码对我来说可行,你在Storyboard中是否正确设置了导航控制器类?我为你制作了一个示例项目:https://github.com/libec/StackOverflow/tree/master/02-Navigation - libec

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