问题 如何判断UIView是否在屏幕上可见?


如果我有 UIView (要么 UIView 子类)是可见的,如何判断它当前是否显示在屏幕上(例如,在当前屏幕外的滚动视图的一部分中)?

或许可以让你更好地了解我的意思, UITableView 有几种方法可以确定当前可见细胞的集合。我正在寻找一些可以对任何给定做出类似决定的代码 UIView


7733
2017-09-26 22:07


起源



答案:


还没试过这个。但 CGRectIntersectsRect()-[UIView convertRect:to(from)View] 和 -[UIScrollView contentOffset] 似乎是你的基本构建块。


10
2017-09-28 02:35



快速额外评论: UIScrollView 滚动时调整其边界 convertRect:[to/from]View: 自动考虑层次结构中任何滚动视图的状态。无需参考 contentOffset  - 你可以直接将一个矩形转换为另一个矩形的坐标空间。 - Tommy


答案:


还没试过这个。但 CGRectIntersectsRect()-[UIView convertRect:to(from)View] 和 -[UIScrollView contentOffset] 似乎是你的基本构建块。


10
2017-09-28 02:35



快速额外评论: UIScrollView 滚动时调整其边界 convertRect:[to/from]View: 自动考虑层次结构中任何滚动视图的状态。无需参考 contentOffset  - 你可以直接将一个矩形转换为另一个矩形的坐标空间。 - Tommy


这是我用来检查哪些UIViews在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
        }
    }
}

2
2018-05-26 06:04





我最近不得不检查我的视图是否在屏幕上。这对我有用:

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
}

1
2017-08-08 00:15



除非你在某处转换坐标,否则这将无效 - n13
如果屏幕是水平的,它不起作用 - Luda


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

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

1
2018-01-07 23:46