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


当前回答

对于超全屏或超上下文模式表示,“is visible”可能意味着它在视图控制器堆栈的顶部,或者只是可见,但被另一个视图控制器覆盖。

要检查视图控制器“is the top view controller”和“is visible”是否有很大不同,你应该检查视图控制器的导航控制器的视图控制器堆栈。

我写了一段代码来解决这个问题:

extension UIViewController {
    public var isVisible: Bool {
        if isViewLoaded {
            return view.window != nil
        }
        return false
    }

    public var isTopViewController: Bool {
        if self.navigationController != nil {
            return self.navigationController?.visibleViewController === self
        } else if self.tabBarController != nil {
            return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
        } else {
            return self.presentedViewController == nil && self.isVisible
        }
    }
}

其他回答

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

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

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

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

上述解决方案存在几个问题。如果你正在使用,例如,一个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;
}

你想要使用UITabBarController的selectedViewController属性。所有附加到标签栏控制器的视图控制器都有一个tabBarController属性集,所以你可以在任何视图控制器的代码中:

if([[[self tabBarController] selectedViewController] isEqual:self]){
     //we're in the active controller
}else{
     //we are not
}

你可以通过window属性来检查

if(viewController.view.window){

// view visible

}else{

// no visible

}

对于那些正在寻找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
}