簡體   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