stephen
stephen

Reputation: 597

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
}

enter image description here

Thanks very much for your help and answer in advance!

Upvotes: 5

Views: 3278

Answers (1)

ATOM
ATOM

Reputation: 78

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

Upvotes: 3

Related Questions