Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

Unable to change navigation bar color during runtime via code?

I tested against iOS 14.5

We would like to provide ability to change the navigation bar color during runtime.

However, I notice the following code no longer has any effect.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        navigationController?.navigationBar.backgroundColor = UIColor.red
        navigationController?.navigationBar.tintColor = UIColor.red
        UINavigationBar.appearance().barTintColor = UIColor.red
    }
}

But, if I did it directly in Storyboard, it works just fine.

enter image description here


We would like to have ability to change the various different color during runtime (via user button clicked)

Does anyone has any idea why the above code broken?

Thanks.

p/s I can confirm the navigationController is not nil.

Upvotes: 0

Views: 298

Answers (2)

Tarun Tyagi
Tarun Tyagi

Reputation: 10102

On iOS 13 & above, you have to use new UINavigationBarAppearance api to get the correct color.

public extension UINavigationBar {

    func applyPlainAppearanceFix(barTintColor: UIColor, tintColor: UIColor) {
        
        if #available(iOS 13, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = barTintColor
            
            self.standardAppearance = appearance
            self.compactAppearance = appearance
            self.scrollEdgeAppearance = appearance
        }
        
        self.isTranslucent = false
        self.barTintColor = barTintColor
        self.backgroundColor = barTintColor
        self.tintColor = tintColor
    }

}

From the call site it should look like

navigationController?.navigationBar.applyPlainAppearanceFix(barTintColor: .red, tintColor: .white)

Upvotes: 1

Menaim
Menaim

Reputation: 1014

Could you try adding this in your AppDelegate and I think it will work, if you didn't want it for all the app then your code is working fine, I've used it and it's working like in the image below:

enter image description here

Upvotes: 0

Related Questions