簡體   English   中英

如何檢查當前是否正在顯示 UIViewController?

[英]How do I check if an UIViewController is currently being displayed?

如何檢查當前是否正在顯示UIViewController

我的UIViewControllers正在偵聽NSNotifications - 即使它們未顯示(即未顯示)。 所以,我可以有10 UIViewController在后台觀察NSNotificationsNSNotificationCenter UIViewController發布和接收NSNotification ,我想知道它當前是否正在顯示。 如果不是,我將只設置一個布爾值,以便在呈現視圖時進行處理。 如果它當前正在顯示,我會做更多的事情,比如立即更新表,等等......

您需要檢查您的視圖控制器是否位於導航控制器的視圖控制器數組堆棧的頂部。 示例代碼是,

if (self.navigationController.topViewController == self) {
    //the view is currently displayed
}

您可以在viewWillAppear方法中使用它來檢查當前視圖是否可見。

檢查它是否連接到窗口。 如果它不是nil則它位於附加到屏幕的層次結構中(當然它可能超出屏幕邊界,被其他視圖覆蓋或設置了隱藏標志)

if (myViewController.view.window) {
  // I'm attached to the window
} else {
  // not attached to the window
}

為此,您可以在viewWillAppearviewWillDisappear方法中使用標志。

為什么不把viewWillDisappear 中的通知監聽器去掉,添加到viewWillAppear 中呢?

編輯:誤讀了他的問題,抱歉。

建議的答案:在 viewDidDisappear 和 viewDidAppear 中設置您自己的標志 (BOOL)。

為每個 ViewController 指定標題,然后通過下面給出的代碼獲取當前 ViewController 的標題。

NSString *currentController = self.navigationController.visibleViewController.title;

Then check it by your title like this

if([currentController isEqualToString:@"myViewControllerTitle"]){

    //write your code according to View controller. 

}

我認為檢查viewController.view.superview應該有效。

現在重提這個問題為時已晚。

要檢查UIViewController的實例當前是否在屏幕頂部或檢查它是否顯示在屏幕上,您可以進行如下檢查:

// Get the topmost view showing on the screen as below
    UIViewController * currentVC = ((UINavigationController*)app.window.rootViewController).visibleViewController;

// Now check whether the viewcontroller you want to show is the same as the currently showing view controller.
    if (currentVC.class == myVC.class) {  // Here myVC is any/new instance of the viewcontroller you would like to check or show (if not shown).
         // If both are same then it returns true and executes this block of code.
    }

另一種基於檢查window屬性的替代方案

if viewController.viewIfLoaded?.window != nil {
    // visible
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM