您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 8 用 UIPresentationController 自訂轉場效果

編輯:iOS 開發綜合

一、UIPresentationController 是什麼

這是 iOS 8 新增的 API,專門用來控制 view controller 之間的跳轉特效。典型需求是:彈出一個大小與位置都自訂的視窗,並在原本的頁面上蓋一層半透明遮罩。在 iOS 8 之前,通常得直接操作 view 層級硬做出來;現在有了官方且結構化的做法。

二、使用步驟

1. 設定目標控制器的轉場代理與樣式

controller.modalPresentationStyle = UIModalPresentationCustom;  // 自訂動畫樣式
controller.transitioningDelegate  = transitionDelegate;        // 需實作 UIViewControllerTransitioningDelegate

2. transitionDelegate 實作三個關鍵方法

// 回傳負責「出現」動畫的物件
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?

3. 控制跳轉的類:繼承 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()      // 決定目標控制器的最終位置與大小

4. 控制動畫的類:繼承 UIViewControllerAnimatedTransitioning

// 動畫持續時間
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval

// 動畫過程的具體安排
func animateTransition(transitionContext: UIViewControllerContextTransitioning)

三、總結:四個組件各司其職

  1. 為目標控制器設定 transitioningDelegate,並把 modalPresentationStyle 改為 Custom。
  2. 該 delegate 回傳三個物件,分別負責出現動畫、消失動畫與版面配置。
  3. UIPresentationController 子類負責轉場「前後」的整體安排,例如加入遮罩、決定 presentedView 的最終 frame,並在 willBegin / didEnd 時機調整遮罩透明度。
  4. UIViewControllerAnimatedTransitioning 子類負責目標控制器出現與消失的具體動畫。

把「版面」與「動畫」拆成兩個獨立物件,是這套設計最漂亮的地方——你可以任意替換其中一種而不影響另一種。API 細節與完整 Demo 建議對照官方文件與 WWDC 2014 的 Custom Transitions Using View Controllers 章節。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved