[swift] 簡易 segue 資料傳輸

Jacob 黃炬楷
Jul 25, 2017 · 2 min read

兩個ViewController
第一個稱為FirstVC,有一個TextField 和一個Button
另一個稱為SeconVC,有一個Label

目的:把FirstVC的Textfield內容,傳到SecondVC的Label去,且透過segue的方式。

由FirstVC的Button作為傳輸的「執行」動作,因此在IBAction中,要「執行」就要透過 performsegue方法:

performSegue(withIdentifier: "(identifier 名稱)", sender: self)

既然要「執行」performsegue,就要為performsegue做「準備」,要做「準備」就要寫 prepare 方法:

func prepare(for segue: UIStoryboardSegue, sender: Any?)

在prepare方法中,要確認segue的identifier是否相同,所以要做if 判斷

並且建立一個物件,來取得SecondVC的property(data),同時要輸入此segue的「目的地」為SecondVC。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {          if segue.identifier == "sendToSecond"{          let secondVC = segue.destination as! SecondVC          secondVC.data = textField.text!
}
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade