37
31

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.

Storyboardで遷移先画面で処理を終えて元の画面に戻る際に値を受け取る

Last updated at Posted at 2016-08-09

概要

今までprotocolとdelegateを使っていましたが、closureで書けることが抜けていたので自分メモ(標記はSwift 3です)。

遷移元のコントローラ

ListViewController.swift
class ListViewController: UIViewController {
  
  // Storyboardで遷移時に呼ばれる
  override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
    // 遷移先のコントローラを取得
    let controller = segue.destinationViewController as! EditViewController 
    
    // 遷移先で処理を終えた後の処理をここで書く
    controller.resultHandler = { data_ in
      print(data_) // テスト
    }
  }

}

遷移先のコントローラ

EditViewController.swift
class EditViewController: UIViewController {
  var resultHandler: ((String) -> Void)?
  
  // 何らかの処理をするメソッド
  func hogeMethod() {
    let data = "テスト"
    
    // handlerに関数がセットされているか確認
    if let handler = self.resultHandler {
      handler(data)
    }
    
    // ListViewControllerに戻る
    self.dismiss(animated: true)
  }
}
37
31
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
37
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?