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


当前回答

如果你正在使用一个UINavigationController,也想处理模式视图,以下是我使用的:

#import <objc/runtime.h>

UIViewController* topMostController = self.navigationController.visibleViewController;
if([[NSString stringWithFormat:@"%s", class_getName([topMostController class])] isEqualToString:@"NAME_OF_CONTROLLER_YOURE_CHECKING_IN"]) {
    //is topmost visible view controller
}

其他回答

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

你可以通过window属性来检查

if(viewController.view.window){

// view visible

}else{

// no 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

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

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

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