Search code examples
iosuinavigationbarswift4viewwillappearviewwilldisappear

UINavigationBar title colour


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)!]


}

Solution

  • 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.