user10733862
user10733862

Reputation:

How to change NavigationBarColor while app running

I use this to set NavigationBarColor before it run:

 UINavigationBar.appearance().barTintColor = Color.NavigationBackground

But in the program,I want to change the NavigationBarColor, So I use this again

 UINavigationBar.appearance().barTintColor = Color.Black

But nothing happen, It still white(Color.Background)
Color is a struct that I defined.
How to change the color correctly? I want to achieve like this:Trying to reload view controller to update the current theme

Upvotes: 1

Views: 268

Answers (5)

VRAwesome
VRAwesome

Reputation: 4803

Use this code to set UINavigationBar color initially in your Appdelegate’s didFinishLaunchingWithOptions.

    UINavigationBar.appearance().isTranslucent = false
    UINavigationBar.appearance().backgroundColor = Color.Background
    UINavigationBar.appearance().barTintColor = Color.Background
    UINavigationBar.appearance().tintColor = UIColor.white

And when you want to change color of UINavigationBar within app, just use these lines of code. Let’s say change color is your button action.

    @IBAction func changeThemeColor(_ sender: UIButton) {

        self.navigationController?.navigationBar.backgroundColor = Color.Black
self.navigationController?.navigationBar.barTintColor = Color.Black
    }

Upvotes: 0

NickCoder
NickCoder

Reputation: 1530

if you want each screen to have different color add below line with color of your choice in view will appear and it will change color for each screen.

Swift 4.2:

//To change Navigation Bar Background Color
UINavigationBar.appearance().barTintColor = UIColor.blue
//To change Back button title & icon color
UINavigationBar.appearance().tintColor = UIColor.white
//To change Navigation Bar Title Color
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

add it in view will appear and then you can see it changing.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.barTintColor = .orange
}

Upvotes: 1

PGDev
PGDev

Reputation: 24341

In your ViewController's viewWillAppear(_:) simply set navigationBar's barTintColor as your required color, i.e.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.barTintColor = .red
}

enter image description here

Upvotes: 0

Deviyani Swami
Deviyani Swami

Reputation: 767

Use the appearance API, and barTintColor color.

UINavigationBar.appearance().barTintColor = UIColor.red

Upvotes: 0

Jins George
Jins George

Reputation: 121

if you want to change the color of navigation bar color

navigationController?.navigationBar.barTintColor = UIColor.black

Upvotes: 0

Related Questions