從一個 Controller 跳到另一個 Controller,主要有兩條路:
PickImageViewController *pickImageViewController = [[PickImageViewController alloc] init];
[self.navigationController pushViewController:pickImageViewController animated:YES];
[pickImageViewController release];
以壓疊/出疊管理控制器,返回時呼叫 popViewControllerAnimated:。
PickImageViewController *pickImageViewController = [[PickImageViewController alloc] init];
[self presentModalViewController:pickImageViewController animated:YES];
// 返回
[self dismissModalViewControllerAnimated:YES];
模態呈現是 iOS 開發中非常實用的技術,UIKit 本身就提供了幾個專為模態顯示設計的控制器,例如 UIImagePickerController。它特別適合以下情境:
這些情境的共同點是:暫時中斷正常流程,目的是收集或展示資訊。
在 view controller A 中模態顯示 view controller B 時,A 是 presenting view controller(彈出方),B 是 presented view controller(被彈出方)。官方建議兩者透過 delegate 溝通。想想 UIImagePickerController 就是透過 UIImagePickerControllerDelegate 與呼叫方互動的——實作時最好比照辦理:在被彈出的 VC 中定義 delegate 協定,由彈出方實作該協定,資料回傳自然順暢。
設定 presenting VC 的 modalPresentationStyle:
typedef enum {
UIModalPresentationFullScreen = 0,
UIModalPresentationPageSheet,
UIModalPresentationFormSheet,
UIModalPresentationCurrentContext,
} UIModalPresentationStyle;
wantsFullScreenLayout 為 YES,還會延伸至狀態列下方。這四種在 iPad 上全部有效;但在 iPhone 與 iPod touch 上,系統一律以 FullScreen 顯示。
設定 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 方法中執行關閉動作。