Swapping rootViewController with animation
transitionWithView
is intended to animate subviews of the specified container view. It is not so simple to animate changing the root view controller. I've spent a long time trying to do it w/o side effects. See:
Animate change of view controllers without using navigation controller stack, subviews or modal controllers?
EDIT: added excerpt from referenced answer
[UIView transitionFromView:self.window.rootViewController.view
toView:viewController.view
duration:0.65f
options:transition
completion:^(BOOL finished){
self.window.rootViewController = viewController;
}];
I am aware this is a quite old question, however, neither the accepted answer nor the alternatives provided a good solution (when the animation finished the navigation bar of the new root view controller blinked from white to the background color, which is very jarring).
I fixed this by snapshotting the last screen of the first view controller, overlaying it over the second (destination) view controller, and then animating it as I wanted after I set the second view controller as root:
UIView *overlayView = [[UIScreen mainScreen] snapshotViewAfterScreenUpdates:NO];
[self.destinationViewController.view addSubview:overlayView];
self.window.rootViewController = self.destinationViewController;
[UIView animateWithDuration:0.4f delay:0.0f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
overlayView.alpha = 0;
} completion:^(BOOL finished) {
[overlayView removeFromSuperview];
}];
EDIT: Swift 3 version of the code:
let overlayView = UIScreen.main.snapshotView(afterScreenUpdates: false)
destinationViewController.view.addSubview(overlayView)
window.rootViewController = destinationViewController
UIView.animate(withDuration: 0.4, delay: 0, options: .transitionCrossDissolve, animations: {
overlayView.alpha = 0
}, completion: { finished in
overlayView.removeFromSuperview()
})