User
User

Reputation: 155

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)
    }

Upvotes: 0

Views: 6538

Answers (4)

Tipu
Tipu

Reputation: 55

UINavigationBar.appearance().backgroundColor = .darkGray

Upvotes: 0

PGDev
PGDev

Reputation: 24341

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

Upvotes: 3

stackich
stackich

Reputation: 5297

Edit your question. It is not clear whether you want your navbar to be clear or red.
However, you can put this in AppDelegate :

let mainVC = MainViewController()
let navigationController = UINavigationController(rootViewController: mainVC)
navigationController.navigationBar.barTintColor = .clear// or .red

Upvotes: 0

Mahsa Yousefi
Mahsa Yousefi

Reputation: 236

Set navigation bar's color of FirstViewController inside ViewWillAppear method.

Upvotes: 0

Related Questions