繁体   English   中英

如何检查视图 controller 是否已在 Swift 中被取消

[英]How to check if a view controller has been dismissed in Swift

如果我像这样呈现一个ViewController

let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: nil)

我想知道ViewController何时被解雇。 我尝试了以下方法:

let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: {
   print("View Dismissed")
})

但这只会让我知道视图是否成功呈现。 这个ViewController不是我创建的,所以我无法更改viewWillDissapear方法。

整个答案基于 OP 无权访问authViewController代码的假设

如果您无权访问authViewController代码,糟糕的解决方案是使用您的视图 controller 的viewWillAppear来查找何时关闭身份验证视图 controller。

基本上,当您在现有视图 controller 上呈现/推送任何视图控制器时,当呈现/推送视图 controller 被解除或弹出viewWillAppear时,您的视图控制器的viewWillDisappear将被类似地调用。

因为viewWillAppear也可能因为其他原因而被调用,并且您不想将其混淆为authViewController关闭,请使用 boolean

private var shouldMonitorAuthViewControllerDismiss = false //declared a instance property

当您实际呈现authViewController时,将 boolean 设置为 true

let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: {
    shouldMonitorAuthViewControllerDismiss = true
})

终于在你viewWillAppear会出现

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        if shouldMonitorAuthViewControllerDismiss {
            //auth view controller is dismissed
        }
        shouldMonitorAuthViewControllerDismiss = false
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM