LoginSignup
0
0

More than 1 year has passed since last update.

画面遷移先に値を渡す

Last updated at Posted at 2022-11-24

前提

Storyboard上でのSegueを設定するパターンとSegueなしの2パターンで解説してきます。
ViewControllerNextViewControllerへの値渡しという前提で進めていきます

Segueあり

簡単な流れ

1. Segueをつける
2. SegueにIDをつける
3. 遷移先に変数を用意する
4. Segueで値を渡す

1. Storyboard上でSegueを設定する

controlを押しながらViewControllerNextViewControllerへ接続します
スクリーンショット 2022-11-24 18.55.28.png

2. SegueにIDをつける

表示されたSegueをタップし、識別子を設定します
スクリーンショット 2022-11-24 18.53.22.png

3. 遷移先に変数を用意する

NextViewController内に値を受け取る箱を用意します

NextViewController
var receiveValue = ""

4. 遷移元でコード上を記述

ViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toNext" {     
            let nextView = segue.destination as! NextViewController
            nextView.receiveValue = "渡したい値"
        }
    }

ViewControllerから遷移した場合、
遷移先のvar receiveValueに値が代入されている状態になります

Segueなし

簡単な流れ

1. StoryboardIDを設定する
2. 遷移先に箱となる変数を用意する
3. 値を渡す

1. StoryboardIDを設定する

Segueなしで画面遷移する場合は、遷移先にStoryboardIDがついていないと遷移できないので、画面遷移先にStoryboardIDをつけます。
スクリーンショット 2022-11-24 18.54.46.png

2. 遷移先に箱となる変数を用意する

NextViewController
var receiveValue = ""

3. 値を渡す

ViewController
@IBAction func NextButtonAction(_ sender: Any) {
    let nextView = self.storyboard?.instantiateViewController(withIdentifier: "Next") as! NextViewController
    nextView.receiveValue = "渡したい値"
    self.navigationController?.pushViewController(nextView, animated: true)
}

ボタンタップ時にViewControllerから遷移し、
遷移先のNextViewController内のvar receiveValueに値が代入されている状態になります

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0