第一種:透過 UINavigationController 堆疊
// 進入下一層 [self.navigationController pushViewController:subTableViewController animated:YES]; // 返回上一層 [self.navigationController popViewControllerAnimated:YES];
這是最符合 iOS 操作習慣的方式,系統會自動處理轉場動畫、返回按鈕與手勢返回。
第二種:Modal 彈出
UIViewController *control = [[UIViewController alloc] init]; [self presentModalViewController:control animated:YES]; [control release]; // 關閉 [self dismissModalViewControllerAnimated:YES];
適合需要使用者完成某件獨立任務的情境,例如登入、表單填寫。
第三種:直接替換 view
[self.view.window addSubview:otherView]; [self.view removeFromSuperview];
這種做法跳出了ViewController的管理體系,較少用於正式專案,通常用於特殊的全域覆蓋層。
1)Delegate 代理模式:子 viewController 定義協議與接口,父 viewController 實作該協議,於子 viewController 退出時把資料回寫給父視圖。這是最典型的反向傳值方式。
2)NSNotificationCenter 通知機制:父 viewController 註冊訊息,子 viewController 發送訊息觸發處理。
// 註冊監聽,setData: 為處理方法
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(setData:)
name:kNotificationMessage
object:nil];
// 發送訊息,userInfo 攜帶資料
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMessage
object:self
userInfo:infoDict];
通知的優點是耦合度低,缺點是資料流向不明顯,除錯時不易追蹤,建議用在跨越多層、關係鬆散的廣播型情境。
3)以資料庫作為中介:子 viewController 把狀態寫入 DB,父 viewController 從 DB 讀出來更新畫面。適合資料量較大或需要持久化的場景。
4)使用 NSUserDefaults 儲存:適合少量、輕量的設定型資料,不建議用來傳遞大物件。
5)透過 AppDelegate 定義全域變量:實作最簡單,但過度使用會讓資料歸屬變得模糊,專案變大後維護成本會明顯上升。
選擇上的一般原則:單純的父子頁面來回,用 delegate 最清楚;跨多個模組的狀態變更,用通知;需要持久化,走資料庫或 NSUserDefaults;至於全域變量,能用就盡量別用。