UINavigationBar title colour

213 Views Asked by At

Why doesn't the navigationBar title change its colour to white when I'm back on my main UIViewController? Here is simple code (viewWillAppear, viewWillDisappear), but it doesn't work, the title stays green when I'm back on this VC. The main colour in app is green too:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIApplication.shared.statusBarStyle = .lightContent

    DispatchQueue.main.async {
    self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name: "Gotham-Medium", size: 20)!]
    }        
}


override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.shared.statusBarStyle = .default

    navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.green, NSAttributedStringKey.font: UIFont(name: "Gotham-Medium", size: 20)!]


}
3

There are 3 best solutions below

7
On BEST ANSWER
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIApplication.shared.statusBarStyle = .lightContent

    DispatchQueue.main.async {
       addTitleLabel()
    }        
}


override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.shared.statusBarStyle = .default
}

func addTitleLabel(){
   var titleLabel: UILabel = UILabel()
   titleLabel.textColor = .white
   titleLabel.textAlignment = .center
   titleLabel.text = "Home"

  self.navigationItem.titleView = titleLabel
}

Call this method form viewWillAppear.

2
On

This isn't going to work how you want because of how the navigation bar is shared between the view controllers and how the system updates it.

What you can do however is put a UILabel in the title of the navigation bar in the font and colour you want. The advantage of this method is that the UILabel only applies to that particular view controller so you never need to reset it.

So in the viewDidLoad of the pushed (second) view controller put this code:

let label = UILabel()
label.font = UIFont(name: "Menlo", size: 20)
label.textColor = .white
label.text = self.navigationItem.title
self.navigationItem.titleView = label

(note you can set the text to anything you want but self.navigationItem.title keeps it simple)

You can now remove the code related to the navigation bar from the viewWillAppear and viewWillDisappear methods.

1
On

You’ve to add navigation title color code in view will appear of previous view controller.