iOS 13 个模态框 - 以编程方式调用滑动关闭

iOS 13 Modals - Calling swipe dismissal programmatically

我想检测呈现模态的视图控制器中的模态关闭。

此方法在检测新的 iOS 13 新卡片模态上的滑动关闭方面效果惊人:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MyIdentifier" {
        segue.destination.presentationController?.delegate = self
    }
}

extension MyController: UIAdaptivePresentationControllerDelegate {    
    func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
        //clean up UI (de-selecting stuff) once modal has been dismissed
    }
}

但是,如果模态通过操作以编程方式解除自身,则不会调用 presentationControllerDidDismiss:

@IBAction func btnDismissTap(_ sender: Any) {
    self.dismiss(animated: true, completion: nil)
}

这是一个错误还是有什么方法可以让我以编程方式调用 "swipe" 解雇是什么,以便我可以用相同的方式检测所有解雇?目前,我正在将额外的 "dismiss" 委托方法编写到我的模态中作为变通方法,这似乎没有必要。

However, presentationControllerDidDismiss is NOT called if the modal dismisses itself programmatically through an action

 self.dismiss(animated: true, completion: nil)

不需要调用它,因为您自己在代码中关闭了模态。您不可能不知道模态已被解雇。您不需要收到解雇信号,因为您首先给出了解雇信号。

您通常不会收到委托方法调用来报告您自己的代码所做的事情。委托方法报告用户操作。如果您自己在代码中所做的一切都作为委托方法调用返回,那就太疯狂了。

正如@matt 所提到的,没有必要通知那些拒绝了委托人观点的人。因为已经知道了。 但是如果您需要调用委托方法,您应该在关闭视图后手动调用它:

@IBAction func btnDismissTap(_ sender: Any) {
    self.dismiss(animated: true) {
        presentationController?.delegate?.presentationControllerDidDismiss?(presentationController!)
    }
}

Mojtaba Hosseini,我一直在寻找答案。

目前,我需要编写一个委托函数来让呈现视图知道用户关闭了模态加上执行 presentationControllerDidDismiss 处理程序来取消滑动:

@IBAction func btnDismissTap(_ sender: Any) {
    self.dismiss(animated: true, completion: {
        self.delegate?.myModalViewDidDismiss()
    })
}

我想以同样的方式处理这两个问题,Mojtaba 的回答对我很有效。但是,如果您在 self.dismiss 完成块内调用它,则不会调用 presentationControllerDidDismiss,您需要在之前调用它。

我调整了我的代码以使用 "presentationControllerWillDismiss"(为清楚起见),并在我以编程方式在我的模式中关闭之前简单地调用了委托并且它工作得很好。

@IBAction func btnDismissTap(_ sender: Any) {
    if let pvc = self.presentationController {
        pvc.delegate?.presentationControllerWillDismiss?(pvc)
    }
    self.dismiss(animated: true, completion: nil)
}

现在,我不再需要创建委托函数来处理代码中的模式关闭,我的滑动处理程序会处理所有情况。

仅供参考,我 "handling" 正在做一些 UI 清理(取消选择等),一旦模式被关闭,呈现 UI。