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


当前回答

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

其他回答

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

如果你正在使用一个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
}

就我的目的而言,在容器视图控制器的上下文中,我已经找到了

- (BOOL)isVisible {
    return (self.isViewLoaded && self.view.window && self.parentViewController != nil);
}

工作得很好。

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

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

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

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

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

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

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