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

iOS Storyboard 教學:兩個 ViewController 之間的傳值技巧

編輯:iOS 開發綜合

Segue 是什麼

在 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,則由系統自動管理。透過這種方式,資料能在轉場前準備完成,讓畫面一載入就拿到所需內容。

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