为什么NavigationBar的背景颜色不变?

时间:2020-07-12 14:11:08

标签: ios swift uinavigationcontroller uinavigationbar ios13

当用户选择其他主题样式时,我需要更改navigationBar背景颜色。

但是奇怪的是,在用户选择“暗”模式之后,进入backgorund,然后又回到前台,如果用户希望改回“亮”模式,导航栏仍为黑色样式,仍然是“ _UIVisualEffectBackdropView”。

但是,如果用户在进入背景之前选择了“浅色”模式,则一切正常。

如何解决此错误?下面是代码和图片:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {
    case 0:
        self.changeToLightColor()
    default:
        self.changeToDarkColor()
    }
}

private func changeToLightColor() {
    self.navigationController?.navigationBar.barStyle = .default
    
    let textAttribute = [NSAttributedString.Key.foregroundColor: UIColor.systemBlue]
    self.navigationController?.navigationBar.titleTextAttributes = textAttribute
}

private func changeToDarkColor() {
    self.navigationController?.navigationBar.barStyle = .black
    
    let textAttribute = [NSAttributedString.Key.foregroundColor: UIColor.systemGreen]
    self.navigationController?.navigationBar.titleTextAttributes = textAttribute
}

enter image description here

非常感谢您的帮助和提前答复!

1 个答案:

答案 0 :(得分:2)

好吧,花了一些时间弄清楚如何解决此问题,并且解决方案非常简单。

只需在barTintColor中将navigationBar设置为需要的颜色即可。

private func changeToLightColor() {
    self.navigationController?.navigationBar.barStyle = .default
    
    //Set to white color
    self.navigationController?.navigationBar.barTintColor = UIColor.white
    
    let textAttribute = [NSAttributedString.Key.foregroundColor: UIColor.systemBlue]
    self.navigationController?.navigationBar.titleTextAttributes = textAttribute
}

private func changeToDarkColor() {
    self.navigationController?.navigationBar.barStyle = .black
            
    //Set to black color
    self.navigationController?.navigationBar.barTintColor = UIColor.black

    let textAttribute = [NSAttributedString.Key.foregroundColor: UIColor.systemGreen]
    self.navigationController?.navigationBar.titleTextAttributes = textAttribute
}

我做完之后,问题就消失了