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


当前回答

亮点:

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

View (macOS):

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

其他回答

对于那些正在寻找Swift 2.2版本的答案的人:

if self.isViewLoaded() && (self.view.window != nil) {
     // viewController is visible
}

Swift 3:

if self.isViewLoaded && (self.view.window != nil) {
         // viewController is visible
}

我在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是否出现。

上述解决方案存在几个问题。如果你正在使用,例如,一个UISplitViewController,主视图总是会返回true

if(viewController.isViewLoaded && viewController.view.window) {
    //Always true for master view in split view controller
}

相反,采用这种简单的方法似乎在大多数情况下都很有效,如果不是所有情况:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    //We are now invisible
    self.visible = false;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //We are now visible
    self.visible = true;
}

我用于模态呈现视图控制器的方法是检查所呈现控制器的类。如果呈现的视图控制器是ViewController2,那么我将执行一些代码。

UIViewController *vc = [self presentedViewController];

if ([vc isKindOfClass:[ViewController2 class]]) {
    NSLog(@"this is VC2");
}

你可以通过window属性来检查

if(viewController.view.window){

// view visible

}else{

// no visible

}