iOSプログラミング with Swift 3


2016.05.27: created by
2017.04.27: revised by

Swiftで別の画面に情報を渡しながら移動する (プログラムで)

  1. 新しいプロジェクトを作成し、 Swiftで別の画面に移動する (プログラムで) をやって下さい。
  2. Main.storyboard上で ViewController2 上に Label を配置し、 ViewController2.swift の myLabel 変数に Outlet でconnectします。






  3. ViewController.swift を変更します。
  4. UIViewController をスーパクラスに持つ ViewController2 の新しいインスタンスを生成し、 インスタンス内の変数に値を設定します。 単なる UIViewController クラスのインスタンスでは passedString 変数を持っていないので、 ここではViewController2 クラスにキャストしなければいけないことに注意しましょう。

    この段階では遷移先のUIViewControllerではUIView をスーパークラスに持つインスタンスはまだ用意されていないので、 アクセスしても nil であることに注意しましょう。代入などしてはいけません(下の例では実行時エラーになる例をコメントにしてあります)。 下の例では、passedString というString型の変数に代入しています。

    ViewController.swiftに追加するコード(マゼンダ色の文字の部分)
    import UIKit
    
    class ViewController: UIViewController {
    
        @IBAction func tapGo(_ sender: AnyObject) {
            let controller = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
            controller.passedString = "passed String"
            controller.myLabel.text = "passed String" // error
            self.present(controller, animated: true, completion: nil)
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    
    }
    
  5. ViewController2.swift を変更します。
  6. passedString変数がnil以外に外から設定されていれば、viewDidLoad関数の中で myLabel.text の値を変更します。

    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()
        }
    
    }
    
  7. 実行すると、Goボタンをクリックすると別の画面に遷移します。2番目の画面でLabelの初期値は "Display2" でしたが、 passedString変数に渡されたString型のデータ "passed String" に変更されて Label が表示されています。
  8. -->
  9. サンプルのプロジェクトはこちら。(Xcode 8.3.2版)


http://nw.tsuda.ac.jp