我有一个标签栏应用程序,有许多视图。有没有办法知道一个特定的UIViewController当前在UIViewController中是可见的?(寻找物业)


当前回答

我根据@ program的回答做了一个快速扩展。

它允许你很容易地检查UIViewController是否在屏幕上,就像这样:

if someViewController.isOnScreen {
    // Do stuff here
}

扩展:

//
//  UIViewControllerExtension.swift
//

import UIKit

extension UIViewController{
    var isOnScreen: Bool{
        return self.isViewLoaded() && view.window != nil
    }
}

其他回答

我需要这个来检查是否视图控制器是当前的视图控制器,我通过检查是否有任何呈现的视图控制器或通过导航器推送,我张贴它以防有人需要这样的解决方案:

if presentedViewController != nil || navigationController?.topViewController != self {
      //Viewcontroller isn't viewed
}else{
     // Now your viewcontroller is being viewed 
}

如果你正在使用一个导航控制器,只是想知道你是否在活动和最顶层的控制器,那么使用:

if navigationController?.topViewController == self {
    // Do something
}

这个答案是基于@mattdipasquale的评论。

如果您有一个更复杂的场景,请参阅上面的其他答案。

我根据@ program的回答做了一个快速扩展。

它允许你很容易地检查UIViewController是否在屏幕上,就像这样:

if someViewController.isOnScreen {
    // Do stuff here
}

扩展:

//
//  UIViewControllerExtension.swift
//

import UIKit

extension UIViewController{
    var isOnScreen: Bool{
        return self.isViewLoaded() && view.window != nil
    }
}

亮点:

window.isVisible
viewController.view.window?.isVisible ?? false

View (macOS):

extension NSViewController {
    var isOnScreen: Bool {
        return ( self.isViewLoaded && view.window != nil )
    }
}

我在uiviewcontroller。h中找到了这些函数。

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);

也许上面的函数可以检测ViewController是否出现。