LoginSignup
2
2

More than 3 years have passed since last update.

segueを使うときの注意点

Posted at

segueは下手すると二回実行される

画面遷移時に値渡しをするのにsegueを使って処理を書くこともあると思いますが、
やり方によっては2回処理がされるため注意が必要です。

普通に動いているように見えますが、デバックしてみるとこんな感じになってます。

qiita.rb
@IBAction func toBlackButton(_ sender: UIButton) {
    performSegue(withIdentifier: "toBlack", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let nextView = segue.destination as! BlackViewController
    print("呼び出された!")
}

スクリーンショット 2019-09-11 21.28.09.png

そんなに呼び出さんでもええんやで・・・。と言いたいが。

原因としては
スクリーンショット 2019-09-11 21.29.45.png

ボタンから直接Controllerを呼び出していたことで、ボタンが押された時にsegueも呼び出されて2回呼び出されるって仕組み(あってるかはわからんけど)

んで対策としては

スクリーンショット 2019-09-11 21.30.48.png

ControllerからControllerへ渡すようにしてあげれば、
Controller内で呼び出されたsegueが起動するだけなので1回での呼び出しになるって感じです。

値を次の画面の配列に入れるって動作をしてたらなぜか2ついっぺんに入るんで判明。

気をつけていきましょう。

2
2
1

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