作者:@翁呀偉呀,授權本站轉載。
這篇文章會說明幾種自定義轉場動畫的方式,並為每種方式附上一個示例——畢竟程式碼才是我們的語言,這樣比較容易上手。主要涵蓋三種做法:
前兩種大家都很熟悉,第三種是 Storyboard 中的拖線,屬於 UIStoryboardSegue 類別,透過繼承它來自定義轉場過程動畫。
操作步驟如下:
1. 建立一個繼承自 NSObject 並遵守 UIViewControllerAnimatedTransitioning 協議的類別。
2. 實作該協議的兩個基本方法:
// 指定轉場動畫的持續時間 func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval // 轉場動畫的具體內容 func animateTransition(transitionContext: UIViewControllerContextTransitioning)
3. 遵守 UINavigationControllerDelegate 協議並實作:
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController)
-> UIViewControllerAnimatedTransitioning?
在此方法中回傳第 1 步建立的動畫類別。
注意:由於 Push 與 Pop 需要兩套動畫,解法是在第 1 步建立兩個檔案,一個負責 Push、一個負責 Pop;然後在第 3 步回傳之前先判斷動畫方向——用 operation == UINavigationControllerOperation.Push 即可區分,再依情況回傳不同的類別。
到這裡就能看到轉場動畫的效果了。但系統預設的 Push 與 Pop 都支援手勢驅動,能依手勢移動距離改變動畫完成度。幸運的是 Cocoa 已整合相關機制,我們只要告訴它百分比即可,所以下一步是手勢驅動。
4. 在第二個 UIViewController 中替 view 加入一個滑動(Pan)手勢,並建立一個 UIPercentDrivenInteractiveTransition 屬性。在手勢的監聽方法中計算移動百分比,用 updateInteractiveTransition() 即時更新;最後在手勢 state 為 ended 或 cancelled 時,依完成度決定要還原還是完成動畫,分別呼叫 cancelInteractiveTransition() 或 finishInteractiveTransition()。
5. 實作 UINavigationControllerDelegate 中另一個回傳 UIViewControllerInteractiveTransitioning 的方法,回傳第 4 步建立的屬性。
此示例源自 Kitten Yang 的部落格,實作 Keynote 中的神奇移動效果,作者以 Swift 重新實作了一遍,原始碼:MagicMove。


func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 1. 取得動畫的來源與目標控制器
let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! DetailViewController
let container = transitionContext.containerView()
// 2. 為 Cell 中的 imageView 做一張截圖並隱藏原物件,
// 讓使用者以為移動的就是 imageView 本身
let snapshotView = fromVC.selectedCell.imageView.snapshotViewAfterScreenUpdates(false)
snapshotView.frame = container.convertRect(fromVC.selectedCell.imageView.frame,
fromView: fromVC.selectedCell)
fromVC.selectedCell.imageView.hidden = true
// 3. 設定目標控制器位置,透明度設為 0,後續動畫中慢慢顯示
toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
toVC.view.alpha = 0
// 4. 依序加入 container,順序不可顛倒
container.addSubview(toVC.view)
container.addSubview(snapshotView)
// 5. 執行動畫
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
snapshotView.frame = toVC.avatarImageView.frame
toVC.view.alpha = 1
}) { (finish: Bool) -> Void in
fromVC.selectedCell.imageView.hidden = false
toVC.avatarImageView.image = toVC.image
snapshotView.removeFromSuperview()
// 動畫結束後務必呼叫,交還 navigation 轉場的管理權
transitionContext.completeTransition(true)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.navigationController?.delegate = self
}
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.Push {
return MagicMoveTransion()
} else {
return nil
}
}
override func collectionView(collectionView: UICollectionView,
didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.selectedCell = collectionView.cellForItemAtIndexPath(indexPath) as! MMCollectionViewCell
self.performSegueWithIdentifier("detail", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
let detailVC = segue.destinationViewController as! DetailViewController
detailVC.image = self.selectedCell.imageView.image
}
}
至此,點擊 Cell 就會執行剛才自定義的動畫。接著加入手勢驅動。
let edgePan = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("edgePanGesture:"))
edgePan.edges = UIRectEdge.Left
self.view.addGestureRecognizer(edgePan)
func edgePanGesture(edgePan: UIScreenEdgePanGestureRecognizer) {
let progress = edgePan.translationInView(self.view).x / self.view.bounds.width
if edgePan.state == UIGestureRecognizerState.Began {
self.percentDrivenTransition = UIPercentDrivenInteractiveTransition()
self.navigationController?.popViewControllerAnimated(true)
} else if edgePan.state == UIGestureRecognizerState.Changed {
self.percentDrivenTransition?.updateInteractiveTransition(progress)
} else if edgePan.state == UIGestureRecognizerState.Cancelled ||
edgePan.state == UIGestureRecognizerState.Ended {
if progress > 0.5 {
self.percentDrivenTransition?.finishInteractiveTransition()
} else {
self.percentDrivenTransition?.cancelInteractiveTransition()
}
self.percentDrivenTransition = nil
}
}
func navigationController(navigationController: UINavigationController,
interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning)
-> UIViewControllerInteractiveTransitioning? {
if animationController is MagicMovePopTransion {
return self.percentDrivenTransition
} else {
return nil
}
}
至此手勢驅動就完成了,但還不能用——因為 Pop 動畫尚未實作,請自行參考原始碼 MagicMove 補上。
modal 轉場即以 presentViewController() 推出的方式,預設情況下第二個視圖從螢幕下方彈出。步驟如下:
1. 建立一個繼承 NSObject 並遵守 UIViewControllerAnimatedTransitioning 協議的類別。
2. 實作 transitionDuration: 與 animateTransition: 兩個方法。
以上兩步與 Push & Pop 相同,接下來才開始不同。
3. 若要以 Modal 方式從第一個 VC 前往第二個,第一個 VC 需遵循 UIViewControllerTransitioningDelegate 協議,並實作 animationControllerForPresentedController: 與 animationControllerForDismissedController: 兩個方法。
4. 在第一個 VC 的 prepareForSegue() 中,把第二個 VC 的 transitioningDelegate 設為 self。
由第 3 步可知,最好也建立兩個動畫類別,一個負責 Present、一個負責 Dismiss;若只建一個,就必須在動畫實作中判斷當前方向。
5. 在第一個 VC 中建立 UIPercentDrivenInteractiveTransition 屬性,並在 prepareForSegue() 中替第二個 VC.view 加入手勢用於 dismiss,監聽方法與 Push & Pop 相同。
6. 實作 UIViewControllerTransitioningDelegate 的另外兩個方法,分別回傳 Present 與 Dismiss 的百分比控制器。
此示例同樣源自 Kitten Yang 的部落格,實作 3D 翻轉效果,以 Swift 重新實作,原始碼:FlipTransion。


動畫細節請直接看程式碼註解。完成 Pop 動畫後即可看到自定義 Modal 轉場效果,剩下手勢驅動。
完整原始碼請見 FlipTransion。
這種方式比較特殊:把 Storyboard 中的拖線與自定義的 UIStoryboardSegue 類別綁定,藉此定義轉場動畫。
先來看 UIStoryboardSegue 的定義:
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning?
可以發現它只有一個方法 perform(),所以很明顯就是覆寫這個方法來自定義轉場動畫。再注意它的屬性 sourceViewController 與 destinationViewController——透過這兩個屬性就能取得轉場動畫的兩個主角,動畫因此可以隨心所欲。
唯一要注意的是:拉線時記得在彈出選項中選擇 custom,才能與自定義的 UIStoryboardSegue 綁定。
由於 perform 所在的是 segue,返回用的上一個控制器稱為 unwind segue。
實作步驟:
此示例為作者自行撰寫,原始碼:SegueTransion。


動畫過程請直接看程式碼,邏輯都很簡單。
這裡要注意:這種方式自定義的轉場動畫無法動態手勢驅動,也就是不能依手勢百分比改變動畫完成度。因此這裡只加入一個簡單的滑動(swipe)手勢。
現在已經可以 present 了,接著實作 dismiss。


再為 SecondViewController 加上手勢,並把手勢監聽方法指向同一個方法即可。完整程式碼請見 SegueTransion。

三種方法的差異可以這樣記:
寫這篇 blog 花了一整天的時間,希望自己和看過的人都能記住。若有錯誤之處,歡迎提出。