本篇延續自定義轉場動畫,說明如何實作動畫物件、手勢驅動,以及使用 UIStoryboardSegue 與 unwind segue 完成返回動畫。
自定義轉場可建立繼承 NSObject 並遵守 UIViewControllerAnimatedTransitioning 的類別。實作 animateTransition 與 transitionDuration,在 containerView 中加入目標視圖,並利用 transform、anchorPoint、陰影圖層等製作翻轉或位移效果。
讓來源 ViewController 遵守 UIViewControllerTransitioningDelegate,並實作 animationControllerForPresentedController 與 animationControllerForDismissedController,分別回傳 push 與 pop 的動畫物件。
若要手勢控制動畫進度,可使用 UIPercentDrivenInteractiveTransition。搭配螢幕邊緣手勢,在開始、變化、結束或取消時,分別呼叫 begin、updateInteractiveTransition、finishInteractiveTransition 或 cancelInteractiveTransition。
另一種方式是建立 UIStoryboardSegue 子類別,並在 Storyboard 中將連線設為 custom。重寫 perform 方法,利用 sourceViewController 與 destinationViewController 取得轉場雙方,再自定義動畫。
返回上一頁可使用 unwind segue。先在來源控制器建立 IBAction 方法,再從目標控制器連到 Exit,設定 identifier。最後在來源控制器重寫 segueForUnwindingToViewController,根據 identifier 回傳自定義的 unwind segue。
Segue 方式簡單,但較不適合百分比手勢驅動;若需要完整互動轉場,建議採用 transitioningDelegate 與 interactive transition。無論哪一種方式,都要注意動畫完成後正確移除臨時視圖、恢復 transform 與 anchorPoint,避免影響後續頁面狀態。