【 iOS 中文開放式課程 】Segue 頁面資料互相傳遞
(XCode 9, iOS 11 , Swift4 )
我們需要您的贊助
學習目標
學習如何使用 Segue 互相傳遞資料
APP UI 介面草圖
操作步驟與說明
接續 「Segue 切換頁面」。
- File -> New File ,新增一個 Cocoa Touch Class
- 檔名為 Scene2ViewController
- 開啟 Scene2ViewController.swift ,加入以下程式
var x2 = 0
// 畫面載入後,將 x2 的資料值 加1
override func viewDidLoad() {
super.viewDidLoad()
//x2 = x2 + 1
x2 += 1
}
- 開啟 ViewController.swift,加入以下程式
var x1 = 0
//當頁面切換時,將 x1 變數值,存到第二場景中的 x2 變數
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destionaion = segue.destination as! Scene2ViewController
destionaion.x2 = x1
}
//第二場景返回時,取出當下的 x2 變數值,將此值存到 x1 ,並列印出來
@IBAction func UnWind(for segue :UIStoryboardSegue)
{
let result = segue.source as! Scene2ViewController
x1 = result.x2
print(x1)
}
- 運行結果