在某些情况下(iPhone X、iOS 13)可以通过从顶部拉动以手势关闭呈现的 View Controller 。
在这种情况下,我似乎找不到通知呈现 View Controller 的方法。我错过了什么?
我发现的唯一方法是向呈现的 View Controller 的 viewDidDisappear 添加一个委托(delegate)方法。
就像是:
class Presenting: UIViewController, PresentedDelegate {
func someAction() {
let presented = Presented()
presented.delegate = self
present(presented, animated: true, completion: nil)
}
func presentedDidDismiss(_ presented: Presented) {
// Presented was dismissed
}
}
protocol PresentedDelegate: AnyObject {
func presentedDidDismiss(_ presented: Presented)
}
class Presented: UIViewController {
weak var delegate: PresentedDelegate?
override func viewDidDisappear(animated: Bool) {
...
delegate?.presentedDidDismiss(self)
}
}
也可以通过通知来管理它,使用 vc 子类,但仍然不能令人满意。
extension Notification.Name {
static let viewControllerDidDisappear = Notification.Name("UIViewController.viewControllerDidDisappear")
}
open class NotifyingViewController: UIViewController {
override open func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.post(name: .viewControllerDidDisappear, object: self)
}
}
必须有更好的方法来做到这一点?
最佳答案
从 iOS 13 开始,Apple 为用户引入了一种新方式 dismiss
通过从顶部拉下呈现的 View Controller 。可以通过实现 UIAdaptivePresentationControllerDelegate
来捕获此事件。到UIViewController
在这种情况下,您正在展示 Presenting
Controller 。然后您可以通过 presentationControllerDidDismiss
方法获得有关此事件的通知。 .这是代码示例:-
class Presenting: UIViewController, UIAdaptivePresentationControllerDelegate {
func someAction() {
let presented = Presented()
presented.presentationController?.delegate = self
present(presented, animated: true, completion: nil)
}
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
// Only called when the sheet is dismissed by DRAGGING.
// You'll need something extra if you call .dismiss() on the child.
// (I found that overriding dismiss in the child and calling
// presentationController.delegate?.presentationControllerDidDismiss
// works well).
}
}
笔记:
dismiss(animated:,completion:)
时触发。方法。 Notification
观察者用于获取用户通过向下滑动关闭 Controller 的事件,因此您可以删除它们。 关于ios - 当使用手势关闭呈现的 View Controller 时如何获得通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62339874/