標籤:
在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 = false12 //源控制器自己負責轉場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 = CGRectZero12 self.persentedDummyView?.frame = CGRectZero13 14 UIView.animateWithDuration(2.0, animations: { () -> Void in15 self.persentedDummyView?.frame = transitionContext.containerView().frame16 toView.frame = UIScreen.mainScreen().bounds17 }, completion: { (_) -> Void in18 //移除傀儡視圖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! HJCPhotoBrowserViewController33 fromVC.view.hidden = true34 //獲得fromVC的快照35 let dummy = fromVC.collectionView.visibleCells().last!.snapshotViewAfterScreenUpdates(false)36 //將傀儡視圖放入containerView37 transitionContext.containerView().addSubview(dummy)38 //執行動畫39 UIView.animateWithDuration(2.0, animations: { () -> Void in40 dummy.frame = CGRectZero41 }, completion: { (_) -> Void in42 //移除傀儡視圖43 dummy.removeFromSuperview()44 //結束45 transitionContext.completeTransition(true)46 })47 }48 }49 }50 51 52 }
【Swift】IOS開發中自訂轉場動畫