iOS Different navigation bar color on different pa

2019-08-03 09:52发布

问题:

How would I change the navigation bar color based on what page the user is on?

I would like to do something similar to what the Vine app uses in the explore category when the user taps a certain category and it turns into the color of the button in a fading format. Any thoughts on how to do this?

回答1:

You can try to set the navigation bar tint color in the prepareForSegue: method (in your controller whit the four buttons) like this

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:"segueIdentifier here"]) { [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]]; } }

Don't forget to reset the navigation bar tint color when you came back (do this in the viewWillAppear)

Or you can try to do this in all your controllers in the method viewWillAppear: like this

- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]]; }



回答2:

Solution for Swift 3.0 (tested on iOS 10)

Hi! I faced the same problem and finally I've found good solution.

Setting the navigation bar's color in viewWillAppear method works fine when you push from a parent to a child view. Transition between navigation bars colors is smooth.

class ChildViewController: UIViewController {

...

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

But it didn't really worked for setting the bar's color in the ParentViewController to the original one. You could notice the color's change, that looked just ugly and unprofessional.

To make the color change smooth when coming back to ParentViewController, do it within the method willMove(toParentViewController parent: UIViewController?) in your ChildViewController:

class ChildViewController: UIViewController {

...

override func willMove(toParentViewController parent: UIViewController?) {
     self.navigationController?.navigationBar.barTintColor = UIColor.red

Thanks to this approach you can set different navigation bar colors on different pages in the one Navigation Controller with smooth colors transitions between view in both ways - going to a child view and also coming back to parent.



回答3:

This is the swift version of how to change navigation bar color on different pages.

You can write this line of code in the viewDidLoad() method of any view controller in which you want to change the color of navigation bar.

self.navigationController!.navigationBar.barTintColor = UIColor.orangeColor()

and then you can use the method viewWillAppear() method so that when you come back to the same view controller from another different controller the color remains same

viewWillAppear(){
self.navigationController!.navigationBar.barTintColor = UIColor.orangeColor()
}