The app I'm working on changes the barTintColor
of its navigation bar when pushing new view controllers. Right now we set that colour in the destination view controller's viewWillAppear:
method, but we have a few issues with that.
With the way we're doing this right now, the navigation bar's colour changes abruptly, while the rest of the bar content animates as usual. What I'd like is for the bar to fade between the source and destination colour. Is there any way to achieve this with public Cocoa Touch APIs?
You can add extra animations that match the timing and animation curve of the view controller transition using UIViewControllerTransitionCoordinator.
A view controller's
transitionCoordinator
will be set after a view controller's animation has started (so inviewWillAppear
of the presented view controller). Add any extra animations usinganimateAlongsideTransition:completion:
on the transition coordinator.An example:
Here is a simpler fix. The issue with
barTintColor
not animating correctly on pop occurs when you try to set the navigation bar appearance inviewWillDisappear
. The fix is to set it inwillMove(toParentViewController:)
instead.The code below will produce a smooth fading transition during both push and pop, and regardless of whether it is initiated by a gesture or button tap. Tested on iOS 10 and 11.
This also works for animating
barStyle
.To get a smooth animation during both push and pop, I had to make the navigation bar transparent and animate my own background color view behind it.
Here's my UINavigationController subclass that handles it:
Usage:
If you want a UIViewController to animate the navigation bar color when it appears, override
viewWillAppear
and callsetBarTintColor
.