Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if UIView is visible to the user?

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

like image 253
jantimon Avatar asked Oct 08 '09 10:10

jantimon


People also ask

How do you check if a view contains a Subview?

Parent view is the view in which we are searching for descendant view and check wether added to parent view or not. if parentView. subviews. contains(descendantView) { // descendant view added to the parent view. }

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.


2 Answers

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.

like image 143
walkingbrad Avatar answered Nov 02 '22 02:11

walkingbrad


You can check if:

  • it is hidden, by checking view.hidden
  • it is in the view hierarchy, by checking view.superview != nil
  • you can check the bounds of a view to see if it is on screen

The only other thing I can think of is if your view is buried behind others and can't be seen for that reason. You may have to go through all the views that come after to see if they obscure your view.

like image 25
mahboudz Avatar answered Nov 02 '22 04:11

mahboudz