繁体   English   中英

如何在 Swift 3 中检查当前的 ViewController?

[英]How to check Current ViewController in Swift 3?

我在ChatViewController ,我导航到其他页面,然后我再次访问了ChatViewController所以当我访问同一页面时,如何在ChatViewController页面上检查我的状态。

override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(true)

    UserDefaults.standard.value(forKey: "ChatView")

    print("view will appear called")
}


override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

    UserDefaults.standard.object(forKey: "ChatView")
    print("view will disappear called")
}

我是否需要设置任何UserDefaults值或其他一些东西。有人可以帮助我吗?提前致谢

Swift 5 和 iOS 15

     if self.navigationController?.presentedViewController != nil && 
    self.navigationController?.presentedViewController is ChatViewController {
        return
}

您可以检查当前导航控制器的导航堆栈。

let viewControllers = self.navigationController!.viewControllers as [UIViewController]
for vc:UIViewController in viewControllers {
    if vc.isKind(of: YourVC.self) {
    }
}

使用用户默认值是没有意义的,因为即使您的应用程序被终止,这些默认值也将是持久的。 这意味着如果用户正在聊天,关闭应用程序,再次打开它,您的用户默认值将表示用户仍在聊天屏幕上。

有多种方式可以显示您的聊天屏幕。 它可能会呈现,可能会被推送到导航栏、标签栏内甚至自定义添加到内容视图中。 所以我会说最好还是使用willAppeardidDisappear 静态值应该可以解决问题:

class ChatViewController: UIViewController {

    static private(set) var currentVisibleInstance: ChatViewController?

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        ChatViewController.currentVisibleInstance = self
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        ChatViewController.currentVisibleInstance = nil
    }

}

现在你可以在任何地方使用它:

let isChatVisible: Bool = ChatViewController.currentVisibleInstance != nil
let currentChatController: ChatViewController? = ChatViewController.currentVisibleInstance

当然,如果您认为合适,您可以将此currentVisibleInstance放在其他某个类中。 您只需更改为SomeOtherClass.currentVisibleChatViewController = self

暂无
暂无

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

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