How to tell if UIViewController's view is visible

Rob Bonner picture Rob Bonner · May 6, 2010 · Viewed 249.7k times · Source

I have a tab bar 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)

Answer

progrmr picture progrmr · May 6, 2010

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

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
}

Since iOS9 it has became easier:

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

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