代码之家  ›  专栏  ›  技术社区  ›  Mike McMaster

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

  •  11
  • Mike McMaster  · 技术社区  · 18 年前

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

    也许能让你更好地理解我的意思, UITableView 有两种确定当前可见单元格集的方法。我正在寻找一些代码,可以作出类似的决定,任何给定的 .

    4 回复  |  直到 9 年前
        1
  •  11
  •   Stunner    13 年前

    我还没试过。但是 CGRectIntersectsRect() , -[UIView convertRect:to(from)View] 和 -[UIScrollView contentOffset]

        2
  •  2
  •   aoakenfo    13 年前

    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
            }
        }
    }
    
        3
  •  1
  •   ecume des jours    13 年前

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

    if (myView.superview){
     //do something with myView because you can assume it is on the screen
    }
    else {
     //myView is not in the view hierarchy
    }
    
        4
  •  0
  •   Steven Hepting    14 年前

    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
    }