這是 iOS 8 新增的 API,專門用來控制 view controller 之間的跳轉特效。典型需求是:彈出一個大小與位置都自訂的視窗,並在原本的頁面上蓋一層半透明遮罩。在 iOS 8 之前,通常得直接操作 view 層級硬做出來;現在有了官方且結構化的做法。
controller.modalPresentationStyle = UIModalPresentationCustom; // 自訂動畫樣式 controller.transitioningDelegate = transitionDelegate; // 需實作 UIViewControllerTransitioningDelegate
// 回傳負責「出現」動畫的物件
optional func animationControllerForPresentedController(
presented: UIViewController,
presentingController presenting: UIViewController,
sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?
// 回傳負責「消失」動畫的物件
optional func animationControllerForDismissedController(
dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
// 回傳負責整體「版面配置」的物件(iOS 8 新增)
optional func presentationControllerForPresentedViewController(
presented: UIViewController,
presentingViewController presenting: UIViewController!,
sourceViewController source: UIViewController) -> UIPresentationController?
/* 初始化方法
presentedViewController:即將跳轉到的目標控制器
presentingViewController:跳轉前的原控制器 */
init(presentedViewController: UIViewController!,
presentingViewController: UIViewController!)
常用屬性與方法:
presentedViewController 要 modal 顯示的視圖控制器 presentingViewController 底層的視圖控制器 containerView() 容器視圖 presentedView() 被展現的視圖 func presentationTransitionWillBegin() // 跳轉即將開始 func presentationTransitionDidEnd(completed: Bool) // 跳轉完成 func dismissalTransitionWillBegin() // dismiss 即將開始 func dismissalTransitionDidEnd(completed: Bool) // dismiss 完成 func frameOfPresentedViewInContainerView() // 決定目標控制器的最終位置與大小
// 動畫持續時間 func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval // 動畫過程的具體安排 func animateTransition(transitionContext: UIViewControllerContextTransitioning)
transitioningDelegate,並把 modalPresentationStyle 改為 Custom。UIPresentationController 子類負責轉場「前後」的整體安排,例如加入遮罩、決定 presentedView 的最終 frame,並在 willBegin / didEnd 時機調整遮罩透明度。UIViewControllerAnimatedTransitioning 子類負責目標控制器出現與消失的具體動畫。把「版面」與「動畫」拆成兩個獨立物件,是這套設計最漂亮的地方——你可以任意替換其中一種而不影響另一種。API 細節與完整 Demo 建議對照官方文件與 WWDC 2014 的 Custom Transitions Using View Controllers 章節。