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

ViewController 頁面跳轉與模態呈現:push、present 與四種轉場風格

編輯:iOS 開發綜合

兩種基本的頁面跳轉

從一個 Controller 跳到另一個 Controller,主要有兩條路:

1. 透過 UINavigationController 堆疊

PickImageViewController *pickImageViewController = [[PickImageViewController alloc] init];
[self.navigationController pushViewController:pickImageViewController animated:YES];
[pickImageViewController release];

以壓疊/出疊管理控制器,返回時呼叫 popViewControllerAnimated:。

2. 透過 UIViewController 自身模態呈現

PickImageViewController *pickImageViewController = [[PickImageViewController alloc] init];
[self presentModalViewController:pickImageViewController animated:YES];

// 返回
[self dismissModalViewControllerAnimated:YES];

模態呈現的主要用途

模態呈現是 iOS 開發中非常實用的技術,UIKit 本身就提供了幾個專為模態顯示設計的控制器,例如 UIImagePickerController。它特別適合以下情境:

  1. 收集使用者輸入的資訊;
  2. 臨時呈現一段內容;
  3. 臨時切換工作模式;
  4. 響應設備方向變化(為不同方向準備不同介面);
  5. 顯示一個新的 view 層級。

這些情境的共同點是:暫時中斷正常流程,目的是收集或展示資訊。

幾個關鍵概念

presenting VC 與 presented VC

在 view controller A 中模態顯示 view controller B 時,A 是 presenting view controller(彈出方),B 是 presented view controller(被彈出方)。官方建議兩者透過 delegate 溝通。想想 UIImagePickerController 就是透過 UIImagePickerControllerDelegate 與呼叫方互動的——實作時最好比照辦理:在被彈出的 VC 中定義 delegate 協定,由彈出方實作該協定,資料回傳自然順暢。

Modal Presentation Styles(呈現風格)

設定 presenting VC 的 modalPresentationStyle:

typedef enum {
    UIModalPresentationFullScreen = 0,
    UIModalPresentationPageSheet,
    UIModalPresentationFormSheet,
    UIModalPresentationCurrentContext,
} UIModalPresentationStyle;
  • FullScreen:被呈現的 VC 填滿全螢幕。若 presenting VC 的 wantsFullScreenLayout 為 YES,還會延伸至狀態列下方。
  • PageSheet:高度等同螢幕,寬度在縱向時等同螢幕寬;未覆蓋區域變暗並阻擋點擊。縱向時效果等同 FullScreen,橫向時兩側會留下變暗區域。
  • FormSheet:寬高都小於螢幕,置中顯示,四周留出變暗區域。
  • CurrentContext:呈現方式與 presenting VC 的父 VC 一致。

這四種在 iPad 上全部有效;但在 iPhone 與 iPod touch 上,系統一律以 FullScreen 顯示。

Modal Transition Style(轉場動畫)

設定 presented VC 的 modalTransitionStyle:

typedef enum {
    UIModalTransitionStyleCoverVertical = 0,   // 由下往上滑入
    UIModalTransitionStyleFlipHorizontal,      // 水平翻轉
    UIModalTransitionStyleCrossDissolve,       // 交錯溶解
    UIModalTransitionStylePartialCurl,         // 部分翻頁
} UIModalTransitionStyle;

這四種動畫不受裝置限制,iPhone 與 iPad 都會依指定風格呈現。

關閉模態畫面

dismissModalViewControllerAnimated:            // 即將廢棄,不建議繼續使用
dismissViewControllerAnimated:completion:     // 建議採用

誰該呼叫?原則是「誰污染誰治理」——由 presenting VC 出面關閉 presented VC。這樣做有個好處:若同一個 VC 依使用者操作會彈出不同類型的畫面,關閉時直接呼叫 [self dismiss...] 即可,不必去記得自己當初彈的是哪一種。

系統在這裡也做了優化:當你在 presented VC 內部呼叫這個方法時,系統會自動把訊息轉交給對應的 presenting VC。因此不論是被誰彈出來的,需要消失時直接關掉自己就行。實務上如何選擇要看情況——若 presented VC 需要回傳資料給 presenting VC,建議還是在 presenting VC 實作的 delegate 方法中執行關閉動作。

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