[英]How to get notified when a presented view controller is dismissed with a gesture?
在某些情况下(iPhone X,iOS 13)可以通过从顶部拉动以手势关闭呈现的视图控制器。
在这种情况下,我似乎找不到通知呈现视图 controller 的方法。 我错过了什么?
我发现的唯一方法是将委托方法添加到呈现视图 controller 的 viewDidDisappear 中。
就像是:
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 引入了一种新方法,用户可以通过从顶部拉下视图 controller 来dismiss
呈现的视图。 可以通过将UIViewController
实现到您正在演示的UIAdaptivePresentationControllerDelegate
来捕获此事件,在本例中为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 的事件,因此您可以删除它们。 采用UIAdaptivePresentationControllerDelegate
并实现presentationControllerDidAttemptToDismiss
(iOS 13+)
extension Presenting : UIAdaptivePresentationControllerDelegate {
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
presentationController.presentingViewController.presentedDidDismiss(self)
}
}
UIPresentationController
有一个属性presentingViewController
。 这个名字是不言自明的。 您不需要显式委托协议。
实际上调用该方法是为了能够显示一个对话框,例如在关闭 controller 之前保存更改。 您还可以实现presentationControllerDidDismiss()
并且不要向彼此相关的控制器发布通知。 这是不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.