Reputation: 7591
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
.
Upvotes: 12
Views: 15959
Reputation: 11942
Not tried any of this yet. But CGRectIntersectsRect()
, -[UIView convertRect:to(from)View]
and -[UIScrollView contentOffset]
seem to be your basic building blocks here.
Upvotes: 11
Reputation: 944
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
}
}
}
Upvotes: 2
Reputation: 2513
if you are primarily worried about releasing an object that is not in the view hierarchy, you could test to see if it has a superview, as in:
if (myView.superview){
//do something with myView because you can assume it is on the screen
}
else {
//myView is not in the view hierarchy
}
Upvotes: 1
Reputation: 12504
I recently had to check whether my view was onscreen. This worked for me:
CGRect viewFrame = self.view.frame;
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
// We may have received messages while this tableview is offscreen
if (CGRectIntersectsRect(viewFrame, appFrame)) {
// Do work here
}
Upvotes: 0