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
.
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.
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.
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.
Not tried any of this yet. But CGRectIntersectsRect()
, -[UIView convertRect:to(from)View]
and -[UIScrollView contentOffset]
seem to be your basic building blocks here.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With