在 Storyboard 中,兩個畫面之間的轉場通常由 Segue 負責。當使用者觸發轉場時,系統會呼叫 prepareForSegue:sender:,讓開發者在畫面切換前準備資料。這也是 Storyboard 傳值最常見的方式。
先在 Storyboard 中為 Segue 設定 identifier,例如 SimpleSegueToSecondViewController。接著在 prepareForSegue:sender: 中,可從 segue 取得 sourceViewController、destinationViewController 與 identifier,再依 identifier 判斷是否要傳值。
if ([[segue identifier] isEqualToString:@"SimpleSegueToSecondViewController"]) {
ZYSecondViewController *viewController = [segue destinationViewController];
viewController.str = @"Hello";
}
在第二個 ViewController 中,只要宣告對應屬性,例如 NSString 類型的 str,就能在 viewDidLoad 中讀取。若使用 MRC,記得在 dealloc 中釋放;若使用 ARC,則由系統自動管理。透過這種方式,資料能在轉場前準備完成,讓畫面一載入就拿到所需內容。