69
68

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 3】UIStoryboardSegue をコードから呼んで画面遷移

Last updated at Posted at 2016-09-12

UIStoryboardSegue をコードから呼ぶ時の記述をメモ。
FirstViewController から SecondViewController へ画面遷移したいとする。

Storyboard で UIStoryboardSegue を作成

Storyboard で FirstViewController を Ctrl + ドラッグで SecondViewController へつなぐ。
identifier を設定しておく。ここでは toSecondViewController とする。

画面遷移したいタイミングで performSegue

画面遷移を行いたいタイミングで performSegue を呼ぶ。

FirstViewController.swift

class FirstViewController: UIViewController {

    // Anything...

    func segueToSecondViewController() {
        self.performSegue(withIdentifier: "toSecondViewController", sender: nil)
    }

}


画面遷移先に何かしらを受け渡したい場合

performSeguesender 引数は Any? 型。
画面遷移先に何かしらを受け渡したい場合は sender にセットし、以下のようにする。

FirstViewController.swift

class FirstViewController: UIViewController {

    let parameters = ["hello": "こんにちは", "goodbye": "さようなら"]

    // Anything...

    func segueToSecondViewController() {
        self.performSegue(withIdentifier: "toSecondViewController", sender: self.parameters)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toSecondViewController" {
            let secondViewController = segue.destination as! SecondViewController
            secondViewController.parameters = sender as! [String : String]
        }
    }

}


sender のダウンキャストの時に、画面遷移先と型が一致するようにする。

SecondViewController.swift

class SecondViewController: UIViewController {

    var parameters: [String : String] = [:] // 画面遷移後は ["hello": "こんにちは", "goodbye": "さようなら"]

    // Anything...
}
69
68
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
69
68

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?