12
6

More than 3 years have passed since last update.

【iOS13】モーダルをスワイプで閉じないようにする

Last updated at Posted at 2019-11-22

modalPresentationStyle = .pageSheet で表示されたモーダルをスワイプで閉じないようにする

公式のサンプルがあるのだが、イマイチ読みづらい…ような気がした:frowning2:
特に、presentationController.delegateへの受け渡しが遷移元に書いてあるので、見落としてしまう。
PageSheetDismiss_1.png

Storyboard

PageSheetDismiss.png

ViewController

class PageSheetViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // UIAdaptivePresentationControllerDelegateを渡す
        navigationController?.presentationController?.delegate = self
    }
}

extension PageSheetViewController: UIAdaptivePresentationControllerDelegate {
    // true: スワイプで閉じる false: スワイプで閉じない
    func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
        false
    }

    // スワイプで閉じない場合に実行したい処理
    func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {

        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "閉じる", style: .default) { _ in
            self.dismiss(animated: true)
        })
        alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
        present(alert, animated: true)
    }
}

とりあえず動かしたい場合はGithubへ

疑問

NavigationControllerを配置しないと実現できなかった。
navigationController?.presentationController?.delegate = selfpresentationController?.delegate = selfと書きたくなるが、これはできない。

参考

【iOS13】.pageSheetなmodalのdismiss時のライフサイクル・制御について
UIAdaptivePresentationControllerDelegate でできることについて参考になりました。
詳細な挙動が知りたい場合は読んでおくといいと思います。

iOS13からのUIModalPresentationStyle.pageSheetでユーザにプルダウンで閉じられないようにする方法
サンプルコードでなぜhasChangesを使うのかの考察が参考になりました。

WWDCのセッション動画

12
6
2

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
12
6