iOSプログラミング with Swift 3


2016.05.27: created by
2017.04.27: revised by

Swiftで別の画面に情報を渡しながら移動する (Segue で)

  1. 新しいプロジェクトを作成し、Swiftで別の画面に情報を渡しながら移動する (Segue で)をやっておく。
  2. Main.storyboard上で ViewController と ViewController2 を結ぶセグウェイを選択して、 Attribute Inspector 上で Storyboard Segue の Identifier に名前を設定します。ここでは "SegueToVC2" としました。






  3. Main.storyboard上で ViewController2 上に Label を配置し、 ViewController2.swift の myLabel 変数に Outlet でconnectします。





  4. ViewController.swift と ViewController2.swift を変更します。
  5. prepareForSegue関数を作成して、このViewController からセグウェイで遷移する途中で 遷移先のUIViewController の変数に渡す情報を代入します。 この段階では遷移先のUIViewControllerではUIView をスーパークラスに持つインスタンスはまだ用意されていないので、 アクセスしても nil であることに注意しましょう。代入などしてはいけません(下の例では実行時エラーになる例をコメントにしてあります)。 下の例では、prepareForSegue ではpassedString というString型の変数に代入しており、 遷移先の ViewController2 の viewDidLoad 関数内で myLabel というUILabel! 型変数の text フィールドに代入しています。

    ViewController.swiftに追加するコード(マゼンダ色の文字の部分)
    import UIKit
    
    class ViewController: UIViewController {
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "SegueToVC2" {
                let controller = segue.destination as! ViewController2
                // controller.myLabel?.text = "passed String"   // error
                controller.passedString = "passed String"
                
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    
    }
    
    ViewController2.swiftに追加するコード(マゼンダ色の文字の部分)
    import UIKit
    
    class ViewController2: UIViewController {
        var passedString: String?
        @IBOutlet weak var myLabel: UILabel!
        @IBAction func tapBack(_ sender: AnyObject) {
            dismiss(animated: true, completion: nil)
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            if passedString != nil {
                myLabel.text = passedString
            }
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    
    }
    
  6. 実行すると、Goボタンをクリックすると別の画面に遷移しますが、情報が渡されていることがわかります。
  7. -->
  8. サンプルのプロジェクトはこちら。(Xcode 8.3.2版)


http://nw.tsuda.ac.jp