画面遷移するとき遷移元ののView Controllerのprepareが呼び出されるのでprepareをオーバーライドしてそこで遷移後のView Controllerに渡す。
[iOS] 画面遷移に追加してみよう。ページ1のボタンを押すと、"PAGE2"ってのを渡してページ2ではラベルにその値を表示することにする。
まず、ページ2のView Controllerクラスを追加して、ストーリボードのページ2と紐付ける。
File - New - FileでCocoa Touch Classを選んでSubclassにUIViewControllerを選んでクラス名をViewController2とする。

ストーリボードのページ2とViewController2クラスを紐付けする。
ページ2の図の1の部分を選択。次に2の部分を選択して、ClassでViewController2を選択する。

ViewController2クラスに値を渡すためのプロパティを追加する。あと、viewDidLoadでラベルに値を設定するようにする。ViewController2クラスはこんな感じだ。
import UIKit
class ViewController2: UIViewController {
@IBOutlet weak var label: UILabel!
var message:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label.text = message
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
ページ1のprepareメソッドを追加してViewController2のmessageプロパティに"PAGE2"をセットする。コードはこんな感じだ。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let viewController2:ViewController2 = segue.destination as! ViewController2
viewController2.message = "PAGE2"
}