iOS - 以编程方式切换视图控制器中的自定义动画

时间:2015-09-09 09:31:53

标签: ios swift animation uistoryboard

我正在尝试使用动画以编程方式在swift中切换视图控制器:

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
    }
)

我将动画选项设置为“TransitionFlipFromBottom”,因为我找不到一些淡出动画

那么有没有办法使用自定义动画?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用自定义UIView动画制作转场动画。例如,基本幻灯片转换,新视图从左侧滑入,旧视图向右滑动:

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;
}];

基本前提是设置toView的结束帧和fromView的结束帧,然后使用UIView动画。只需确保从superview中删除fromView,然后nil将其删除,否则可能会造成内存泄漏。您在示例代码中转换的方式将为您处理此步骤。