【Swift】unWindSegueで前画面に戻りつつ値を渡す

どうも、ねこきち(@nekokichi1_yos2)です。

 

今回は、unWindSegue、の使用方法を書いていきます。 

 

解説 

 

手順は、

  1. 画面を用意する(2個以上)
  2. 前画面にunWindSegueを記述
  3. StoryBoardで遷移元にunWindSegueを接続
  4. 遷移元でunWindSegueを実行 

 

画面を用意する(2個以上)

 

今回の画面構成は下記。

  • 前画面:unWindSegue1
  • 遷移元:unWindViewController

 

f:id:nekokichi_yos2:20200809121124p:plain

 

前画面にunWindSegueを記述

 

前画面(unWindSeuge1)にunWindSegueを記述します。

(@IBActionと書かれてますが、UI部品と接続することはありません。)

 

また、引数のunwindSegueには、下記のプロパティが用意されています。

 

今回の場合、遷移元がunWindViewControllerなので、unWindSegue.source、にはunWindViewControllerが格納されます。

 

そして、遷移元の変数に直接、アクセスできます。

(下記では、遷移先のtextFieldの値をlabelに代入しています。)

 

    @IBOutlet weak var label: UILabel!
    
    @IBAction func unwind(_ unwindSegue: UIStoryboardSegue) {
        //unWindViewController
        guard let source = unwindSegue.source as? unWindViewController else { return }
        label.text = source.textField.text
    }

 

StoryBoardで遷移元にunWindSegueを接続

 

前提として、遷移先にunWindSegueを記述する必要があります。

(でないと、接続できません。)

 

StoryBoard上で、unWindViewControllerをExitに接続します。

 

f:id:nekokichi_yos2:20200809122821p:plain

 

先ほど、遷移先で作ったunWindSegueを選択します。

 

f:id:nekokichi_yos2:20200809122825p:plain

 

次は、unWindSegueを選択し、

 

f:id:nekokichi_yos2:20200809122512p:plain

 

Identifierを設定します。

(今回はexit)

 

f:id:nekokichi_yos2:20200809122336p:plain

 

遷移元でunWindSegueを実行 

 

あとは、遷移元でperformSegueを実行するだけです。

(withIdentifierには、StoryBoard上で設定したIdentifierを記述します。)

 

    @IBAction func back(_ sender: Any) {
        performSegue(withIdentifier: "exit", sender: nil)
    }

 

結果

 

f:id:nekokichi_yos2:20200809123534g:plain

 

ソースコード

 

import UIKit

class unWindSegue1: UIViewController {
    
    @IBOutlet weak var label: UILabel!
    
    @IBAction func unwind(_ unwindSegue: UIStoryboardSegue) {
        //unWindViewController
        guard let source = unwindSegue.source as? unWindViewController else { return }
        label.text = source.textField.text
    }

}

 

import UIKit

class unWindViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    
    @IBAction func back(_ sender: Any) {
        performSegue(withIdentifier: "exit", sender: nil)
    }

}

 

参考

 

[Xcodeアプリ開発入門] Part32 Modal遷移時にデータを前の画面に戻す方法

youtu.be