1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】画面遷移先に変数を渡したい

Last updated at Posted at 2020-12-06

どういうことか

遷移前の画面で定義した変数を遷移先の画面に渡したい。

渡す

prepare のメソッドを書いて値を渡す準備をする。
prepare と書いて出てきたものを選択すると自動補完してくれる。

スクリーンショット 2020-12-05 20.05.51.png

ViewController.swift

  // 渡したい変数
  var face = "(´・ω・`)"

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

    // 遷移先のコントローラ名を書く。ここではNextViewController
    let nextVC = segue.destination as! NextViewController
    
    // 受け取る先で定義する変数名(後述)に渡したい変数を代入する  
    nextVC.nextFace = face
  }

遷移先で受け取る

 NextViewController.swift

  // 例えばLabelを設置しておいてそこで受け取る
  @IBOutlet weak var nextLabel: UILabel!
  var nextFace = ""

  override func viewDidLoad() {
        super.viewDidLoad()

      nextLabel.text = nextFace
    }

この記事の場合だと遷移先の画面に設置したLabelに (´・ω・`) が表示される。
実用的なところでは計算した答えとか遷移先に渡すとかがいいと思う。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?