How to tell if UIViewController's view is visible

I have a tabbar application, with many views. Is there a way to know if a particular UIViewController is currently visible from within the UIViewController? (looking for a property)


The view's window property is non-nil if a view is currently visible, so check the main view in the view controller:

[EDIT] Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded. I've added the call to isViewLoaded to avoid this problem.

if (viewController.isViewLoaded && viewController.view.window) {
    // viewController is visible
}

Or if you have a UINavigationController managing the view controllers, you could check its visibleViewController property instead.

Also, in Swift on iOS 9 (or later):

if viewController.viewIfLoaded?.window != nil {
    // viewController is visible
}

这里是@ progrmr的解决方案作为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

There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController , the master view will always return true for

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

Instead, take this simple approach which seems to work well in most, if not all cases:

- (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;
}
链接地址: http://www.djcxy.com/p/87732.html

上一篇: 来自appDelegate的UINavigationcontroller initWithRootViewController,空视图?

下一篇: 如何判断UIViewController的视图是否可见