presentedViewController 更改 KVO

问题描述 投票:0回答:2

我正在尝试侦听presentedViewController 的更改,但该属性看起来并不符合KVO 标准(或者至少我无法从中获取更改)。当 UIViewController 主动呈现时,UIViewController 有没有办法监听变化?

ios uiviewcontroller
2个回答
5
投票

presentedViewController
似乎不符合 KVO 标准,但可以通过覆盖
UIViewController
的相关呈现/消除方法来通知更改:

override func presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) {
    // will present view controller
    super.presentViewController(viewControllerToPresent, animated: flag, completion: completion)
}

override func dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?) {
    super.dismissViewControllerAnimated(flag, completion: completion)
    // did dismiss view controller
}

斯威夫特 4:

override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
...
}

0
投票

试试这个

class ViewController: UIViewController {
    var observation: NSKeyValueObservation?
    override func viewDidLoad() {
        super.viewDidLoad()

        observation = observe(\.presentationController, options: [.old, .new]) { _, change in
            print("presentationController changed")
            if let vc = change.newValue as? UIPresentationController {
                print("presentedViewController: \(vc.presentedViewController.presentedViewController)")
            }
        }
    }

    deinit {
        observation?.invalidate()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.