2
3

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 5 years have passed since last update.

【Swift】 画面遷移時に遷移先画面に値を受け渡す

Posted at

はじめに

アップデートで修正中のアプリで、似たような機能の画面を2つ追加する要件があったんですが、「これ、素直に画面を2つ作るより、遷移元を判定して画面項目の表示を切り替えた方がむしろスマートだと思う」という発想から、じゃあどうやって遷移元の情報を遷移先に渡そうか、というところをフィージビリティ検証しました。

開発環境

端末:MacBook Pro/MacOS 10.14.5(Mojave)
Xcode:10.2.1
Swift:5

やったこと

2つの画面を作り、遷移元画面から遷移先画面へ値が受け渡せることの確認
(受け渡れた値を元に表示切り替え、は検証するまでもないので対象外)

実装サンプルソース

画面イメージ ※画面はStoryboardで作成
遷移元
Simulator Screen Shot - iPad Air 2 - 2019-09-26 at 02.00.42.png
遷移先
Simulator Screen Shot - iPad Air 2 - 2019-09-26 at 02.00.46.png
MotoViewController.swift(遷移元画面)
import UIKit

class MotoViewController: UIViewController {

    // 受け渡す値の入力エリア
    @IBOutlet weak var txtPassString: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    // 「遷移先画面へ」ボタン押下時
    @IBAction func transition(_ sender: Any) {
        let storyboard = self.storyboard
        // 遷移先画面
        let sakiView = storyboard!.instantiateViewController(withIdentifier: "saki") as! SakiViewController
        // 遷移先画面の項目へ受け渡す値をセット
        sakiView.passedString = txtPassString.text!
        // 画面遷移
        self.present(sakiView, animated: true, completion: nil)
    }
}
SakiViewController.swift(遷移先画面)
import UIKit

class SakiViewController: UIViewController {
    
    @IBOutlet weak var txtPassedString: UITextField!
    
    var passedString: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        if (passedString != nil) {
            txtPassedString.text = passedString
        }
    }
}

コードの量としては思っていたよりも少なく実装できました。
が、遷移先画面のStoryboard IDを指定するのを忘れないよう注意が必要。(下の画像を参照)

Screen Shot 2019-09-26 at 3.22.31.png

画面サンプル

GIFでの動作イメージです。
myTransitionImage.gif

青い画面(遷移元)で"test"と入力したのが、黄色い画面(遷移先)に渡されて画面中央のエリアに表示されています。

※GIF作成アプリで動作イメージ見てた時は気づかなかったけど、画面遷移時、画面がすごくチラつきますね。。
 見づらくてスミマセン。。

参考にさせて頂いたサイトなど

カピ通信 - 【Swift/iOS】画面遷移時の値渡し
https://capibara1969.com/1060/#toc10

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?