0
0

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.

画面遷移時に値を渡す方法

Last updated at Posted at 2021-08-30

結論から書くと結果はこんな感じ。

スクリーンショット 2021-08-30 22.23.23.png

スクリーンショット 2021-08-30 22.24.44.png

性別とか年齢とか書いてありますけどそこは無視してください。
作るのめんどくさかったので、個人で作成してるアプリの一部をそのまま撮りました。

 
今回は別のViewControllerから、最初から存在する Main.storyboardと ViewControllerに値を渡し表示するという想定です。
 

まず別のViewControllerのプログラムはこちら。

class 別のViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let nextVC = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
    
        //textFieldの内容ををMain.storyboardのViewControllerの変数に代入
        nextVC.name = textField.text!
    
        present(nextVC, animated: true, completion: nil)

    }
}

  上記ソース↓の部分は

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let nextVC = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController

 
 
↓ようになっている想定です。

スクリーンショット 2021-08-30 22.27.28.png

スクリーンショット 2021-08-30 22.28.07.png

そしてMain.storyboardのViewControllerのソースはこちら。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var nameLabel: UILabel!

    var name = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        nameLabel.text = name
    }
}

 

Segueを使って値を渡す方法もありますが、案件でSegueを使って値を渡すことなんてないのでこちらのやり方で学んだ方がいいかなと。
 

参考までに。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?