Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a UIView is visible and on screen?

If I have a UIView (or UIView subclass) that is visible, how can I tell if it's currently being shown on the screen (as opposed to, for example, being in a section of a scroll view that is currently off-screen)?

To maybe give you a better idea of what I mean, UITableView has a couple of methods for determining the set of currently visible cells. I'm looking for some code that can make a similar determination for any given UIView.

like image 916
Mike McMaster Avatar asked Sep 26 '08 22:09

Mike McMaster


People also ask

How do I know if a Viewcontroller is visible?

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.

What is a hidden view?

A hidden view disappears from its window and does not receive input events. It remains in its superview's list of subviews, however, and participates in autoresizing as usual. Hiding a view with subviews has the effect of hiding those subviews and any view descendants they might have.

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

Not tried any of this yet. But CGRectIntersectsRect(), -[UIView convertRect:to(from)View] and -[UIScrollView contentOffset] seem to be your basic building blocks here.

like image 127
schwa Avatar answered Oct 11 '22 13:10

schwa


Here's what I used to check which UIViews were visible in a UIScrollView:

for(UIView* view in scrollView.subviews) {
    if([view isKindOfClass:[SomeView class]]) {

        // the parent of view of scrollView (which basically matches the application frame)
        CGRect f = self.view.frame; 
        // adjust our frame to match the scroll view's content offset
        f.origin.y = _scrollView.contentOffset.y;

        CGRect r = [self.view convertRect:view.frame toView:self.view];

        if(CGRectIntersectsRect(f, r)) {
            // view is visible
        }
    }
}
like image 30
aoakenfo Avatar answered Oct 11 '22 13:10

aoakenfo