简体   繁体   中英

Why the NavigationBar background color not change?

I need to change the navigationBar background color when the user chooses different Theme style.

But the strange thing is, after the user chooses the "Dark" mode, then enter into backgorund, then back to foreground, if the user wants changing back to "Light" mode, the navigation bar is still in black style, there is a "_UIVisualEffectBackdropView" remains dark.

But if the user chooses "Light" mode before enter into background, then everything works fine.

How can I fix this bug? Below is the code & pic:

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
}

在此处输入图像描述

Thanks very much for your help and answer in advance!

Well, it has taken a little time to figure out how to fix this, and the solution is very simple.

Just set barTintColor in navigationBar to color you need.

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
}

After I did it, the issue has gone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM