在IOS开发中,我们model另外一个控制器的时候,一般都使用的自定义的转场动画。
其实我们可以自定义一些转场动画。达到不同的转场效果。
步骤如下:(photoBrowser是目标控制器)
1. 在源控制器中,设置目标控制器的转场代理为 self
1 //设置Model转场代理 2 photoBrowser.transitioningDelegate = self
2.同时设置目标控制器的model类型
1 //设置Model类型 2 photoBrowser.modalPresentationStyle=UIModalPresentationStyle.Custom
3.定义一个变量记录转场还是退场 (true为转场,false为退场
1 var isPersent = false
4.在源控制器中设置跳转,目标控制器中设置关闭(动画要选择true)
1 presentViewController(photoBrowser, animated: true) { () -> Void in } 2 dismissViewControllerAnimated(true){SVProgressHUD.dismiss()}
5. 源控制器遵守两个代理
UIViewControllerTransitioningDelegate,
UIViewControllerAnimatedTransitioning
6. 源控制器实现 2 个代理方法
1 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{ 2 //转场 3 isPersent = true 4 //源控制器自己负责转场 5 return self 6 } 7 8 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{ 9 10 //退场 11 isPersent = false 12 //源控制器自己负责转场 13 return self 14 }
7.源控制器再实现2个代理方法
1 //转场时间 2 func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval 3 4 //转场上下文,负责转场动画的具体内容 5 func animateTransition(transitionContext: UIViewControllerContextTransitioning){ 6 //转场动画 7 if isPersent{ 8 if let toView = transitionContext.viewForKey(UITransitionContextToViewKey){ 9 //将傀儡视图(用于动画时展现的画面)加入containerView() 10 transitionContext.containerView().addSubview(self.persentedDummyView!) 11 toView.frame = CGRectZero 12 self.persentedDummyView?.frame = CGRectZero 13 14 UIView.animateWithDuration(2.0, animations: { () -> Void in 15 self.persentedDummyView?.frame = transitionContext.containerView().frame 16 toView.frame = UIScreen.mainScreen().bounds 17 }, completion: { (_) -> Void in 18 //移除傀儡视图 19 self.persentedDummyView?.removeFromSuperview() 20 //加入要正常显示的视图 21 transitionContext.containerView().addSubview(toView) 22 //结束 23 transitionContext.completeTransition(true) 24 }) 25 } 26 } 27 //退场动画 28 if !isPersent{ 29 if let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey){ 30 31 //隐藏目标控制器 32 let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! HJCPhotoBrowserViewController 33 fromVC.view.hidden = true 34 //获得fromVC的快照 35 let dummy = fromVC.collectionView.visibleCells().last!.snapshotViewAfterScreenUpdates(false) 36 //将傀儡视图放入containerView 37 transitionContext.containerView().addSubview(dummy) 38 //执行动画 39 UIView.animateWithDuration(2.0, animations: { () -> Void in 40 dummy.frame = CGRectZero 41 }, completion: { (_) -> Void in 42 //移除傀儡视图 43 dummy.removeFromSuperview() 44 //结束 45 transitionContext.completeTransition(true) 46 }) 47 } 48 } 49 } 50 51 52 }