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


当前回答

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

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

其他回答

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

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

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

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

下面是@ program作为UIViewController类别的解决方案:

// UIViewController+Additions.h

@interface UIViewController (Additions)

- (BOOL)isVisible;

@end


// UIViewController+Additions.m

#import "UIViewController+Additions.h"

@implementation UIViewController (Additions)

- (BOOL)isVisible {
    return [self isViewLoaded] && self.view.window;
}

@end

好的观点是,如果视图已经在窗口层次结构堆栈中出现。 因此,我们可以扩展类来实现这个功能。

extension UIViewController {
  var isViewAppeared: Bool { viewIfLoaded?.isAppeared == true }
}

extension UIView {
  var isAppeared: Bool { window != nil }
}