Search code examples
iosswiftuinavigationcontrolleruinavigationbar

swift: change the color of the navigation bar


I am using a FirstViewController with a red tint color navigation bar. When I go to next SecondViewController I use this code that clear navigation bar color:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)

But when I go back to FirstViewController my navigation bar color is not red. It is clear. But it should be red. How to fix it?

code in FirstViewController:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.navigationController?.navigationBar.prefersLargeTitles = true
        self.navigationItem.largeTitleDisplayMode = .always
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        self.navigationController?.navigationBar.barTintColor = UIColor(red: 239/255, green: 210/255, blue: 166/255, alpha: 1.0)
    }

Solution

  • Instead of barTintColor, use backgroundColor to change the navigationBar'r color, i.e.

    In FirstVC,

    class FirstVC: UIViewController {
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            self.navigationController?.navigationBar.prefersLargeTitles = true
            self.navigationItem.largeTitleDisplayMode = .always
            self.navigationController?.navigationBar.shadowImage = UIImage()
            self.navigationController?.navigationBar.backgroundColor = .red //here...
        }
    }
    

    In SecondVC,

    class SecondVC: UIViewController {
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            self.navigationController?.navigationBar.backgroundColor = .clear //here...
        }
    }
    

    enter image description here