Determine if UIView is visible to the user?

jantimon picture jantimon · Oct 8, 2009 · Viewed 81.3k times · Source

is it possible to determine whether my UIView is visible to the user or not?

My View is added as subview several times into a Tab Bar Controller.

Each instance of this view has a NSTimer that updates the view.

However I don't want to update a view which is not visible to the user.

Is this possible?

Thanks

Answer

walkingbrad picture walkingbrad · Nov 12, 2013

For anyone else that ends up here:

To determine if a UIView is onscreen somewhere, rather than checking superview != nil, it is better to check if window != nil. In the former case, it is possible that the view has a superview but that the superview is not on screen:

if (view.window != nil) {
    // do stuff
}

Of course you should also check if it is hidden or if it has an alpha > 0.

Regarding not wanting your NSTimer running while the view is not visible, you should hide these views manually if possible and have the timer stop when the view is hidden. However, I'm not at all sure of what you're doing.