今回は、Swift の Modal が閉じられたことを親画面で検知する方法についてです。
参考にさせていただいた記事はこちらから。
【Swift】Modalで表示した子画面の閉じるイベントを親画面で検知する – Qiita
https://qiita.com/o_mo_te/items/9ffd22873303d873bbed
サンプルコードは下記のとおりです。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Modal を表示する
let modalViewController = self.storyboard?.instantiateViewController(withIdentifier: "modalViewController") as! ModalViewController
modalViewController.presentationController?.delegate = self
present(modalViewController, animated: true, completion: nil)
}
}
extension ViewController: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
// モーダルの dismiss を検知
// モーダルが閉じた時に実行したい処理を追加
}
}
重要なのが 14~19行目の presentationControllerDidDismiss メソッドで、こちらでモーダルが閉じられたことを検知できます。
追加するコードはこれだけです。
こちらを追加したプロジェクトを Simulator で実行したところ、Modal を閉じたタイミングで presentationControllerDidDismiss が呼び出されていることを確認できました!
あとは、この関数内に実行したい処理を記述すればOKですね。
以上、Swift で Modal を閉じたことを親の ViewController で検知する方法についてでした。
ご参考になれば幸いです。