Reputation: 622
I'm trying to switch view controllers in swift programmatically with animation:
var storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
var appDelegateTemp : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var view : UIView? = appDelegateTemp.window!.rootViewController?.view
destinationViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as? UIViewController
UIView.transitionFromView(view!, toView: destinationViewController!.view, duration: 0.5, options: UIViewAnimationOptions.TransitionFlipFromBottom,
completion: { (completed : Bool) -> Void in
var application = UIApplication.sharedApplication()
var appDelegateTemp : AppDelegate = application.delegate as! AppDelegate
appDelegateTemp.window!.rootViewController = self.destinationViewController
}
)
I set animation options to "TransitionFlipFromBottom", cause I couldn't find some fade out animation
So is there a way to use custom animations?
Upvotes: 1
Views: 979
Reputation: 151
Yeah, you can animate the transition however you would like using custom UIView
animations. For example, a basic slide transition where the new view slides in from the left and the old view slides out to the right:
CGSize screenSize = [UIScreen mainScreen].bounds.size;
CGRect toViewStartFrame = toView.frame;
CGRect toViewEndFrame = fromView.frame;
CGRect fromViewEndFrame = fromView.frame;
toViewStartFrame.origin.x = -screenSize.width;
fromViewEndFrame.origin.x = screenSize.width;
[fromView.superview addSubview:toView];
toView.frame = toViewStartFrame;
[UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:0 animations:^{
toView.frame = toViewEndFrame;
fromView.frame = fromViewEndFrame;
} completion:^(BOOL finished) {
[fromView removeFromSuperview];
fromView = nil;
}];
The basic premise is to set the toView
's end frame and the fromView
's end frame, then use UIView
animations. Just make sure to remove the fromView
from the superview and nil
it out afterward, or you may create a memory leak. The way you transition in example code handles this step for you.
Upvotes: 2