如何判断一个UIView是否可见并在屏幕上显示?

12
如果我有一个可见的UIView(或UIView子类),如何判断它当前是否正在屏幕上显示(而不是在当前屏幕外的滚动视图部分中,例如)?
也许可以更好地说明我的意思,UITableView有几个方法可以确定当前可见单元格集。 我正在寻找一些代码,可以对任何给定的UIView进行类似的确定。
4个回答

11

我还没有尝试过这些方法,但是CGRectIntersectsRect()-[UIView convertRect:to(from)View]-[UIScrollView contentOffset] 看起来是你在这里的基本构建块。


快速额外的注释:UIScrollView在滚动时会调整其边界,因此convertRect:[to/from]View:自动考虑了层次结构中任何滚动视图的状态。无需引用contentOffset - 您可以直接将一个矩形转换为另一个坐标空间。 - Tommy

2

这是我用来检查在UIScrollView中哪些UIView是可见的:

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
        }
    }
}

1

如果您主要担心释放不在视图层次结构中的对象,可以测试其是否具有超级视图,例如:

if (myView.superview){
 //do something with myView because you can assume it is on the screen
}
else {
 //myView is not in the view hierarchy
}

0

最近我需要检查我的视图是否在屏幕上。这个方法对我很有效:

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
}

只有在 self.view 的所有父视图都没有相对于窗口的偏移原点时,此方法才有效。 - Richard Groves

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接