🔗 Segueとは?
Storyboard上でViewControllerとViewControllerを線(矢印)でつなぎ、遷移の種類を選ぶことで、iOSアプリにおける画面遷移が定義されます。
🎬 Segueの種類(種類ごとの動き)
- Show(Push):ナビゲーションスタックにプッシュ(NavigationControllerが必要)
- Present Modally:モーダル表示(全画面・シートなど)
- Custom:独自アニメーションの遷移(拡張向け)
- Unwind Segue:元の画面に戻るための仕組み
🧰 Segueの作り方
- Storyboard上でボタンと遷移先ViewControllerをControlキーを押しながらドラッグ
- 「Show」や「Present Modally」などを選択
- 選択したSegueに Identifier を設定(Attributes Inspector)
💻 コードからSegueを実行する
performSegue(withIdentifier: "toSecondView", sender: self)
このメソッドを使うには、Storyboard上のSegueにID(Identifier)を設定しておく必要があります。
📦 データの受け渡し(prepare(for segue:))
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toSecondView" {
if let nextVC = segue.destination as? SecondViewController {
nextVC.receivedText = "こんにちは!"
}
}
}
遷移先のプロパティに値を渡したいときはこのメソッドで設定します。
🔙 Unwind Segue(戻るSegue)
- 元の画面(戻り先)に以下のようなメソッドを追加:
@IBAction func unwindToFirst(_ segue: UIStoryboardSegue) {
print("戻ってきたよ")
}
- Storyboard上で戻りたいボタンから「Exit」にドラッグして
unwindToFirst:を選択
📌 注意点
- SegueはStoryboard上でIDがないと
performSegue()で呼び出せません - Unwind Segueは関数名のつけ方と接続先に注意
- NavigationControllerがないと「Show」はエラーになる場合あり