25

检查当前 UIScrollView 的 contentView 上是否可见 UIView 的最简单和最优雅的方法是什么?有两种方法,一种是涉及到 UIScrollView 的 contentOffset.y 位置,另一种是转换 rect 区域?

4

7 回答 7

23

如果您正在尝试确定视图是否已在屏幕上滚动,请尝试以下操作:

    CGRect thePosition =  myView.frame;
    CGRect container = CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, scrollView.frame.size.width, scrollView.frame.size.height);
    if(CGRectIntersectsRect(thePosition, container))
    {
        // This view has been scrolled on screen
    }
于 2013-07-23T09:48:22.083 回答
19

Swift 5:如果您想触发一个事件来检查整个 UIView 在滚动视图中是否可见:

extension ViewController: UIScrollViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.bounds.contains(targetView.frame) {
            // entire UIView is visible in scroll view
        }
    }

}
于 2018-12-21T14:44:56.130 回答
8

在您的滚动视图委托中实现scrollViewDidScroll:并手动计算哪些视图是可见的(例如,通过检查是否CGRectIntersectsRect(scrollView.bounds, subview.frame)返回 true。

于 2012-06-04T19:25:49.023 回答
5

为 Swift 3 更新

var rect1: CGRect!
// initialize rect1 to the relevant subview
if rect1.frame.intersects(CGRect(origin: scrollView.contentOffset, size: scrollView.frame.size)) {
        // the view is visible
    }
于 2016-10-23T21:39:14.430 回答
2

我认为你的想法是正确的。如果是我,我会这样做:

//scrollView is the main scroll view
//mainview is scrollview.superview
//view is the view inside the scroll view

CGRect viewRect = view.frame;
CGRect mainRect = mainView.frame;

if(CGRectIntersectsRect(mainRect, viewRect))
{
    //view is visible
}
于 2012-06-04T19:25:10.163 回答
2

José 的解决方案对我来说不太奏效,它会在我的视图出现在屏幕上之前检测到它。如果 José 的简单解决方案不适合您,以下相交代码在我的 tableview 中完美运行。

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let viewFrame = scrollView.convert(targetView.bounds, from: targetView)
        if viewFrame.intersects(scrollView.bounds) {
            // targetView is visible 
        }
        else {
            // targetView is not visible
        }
    }
于 2021-02-10T15:20:15.730 回答
0

考虑插图的解决方案

public extension UIScrollView {
    
    /// Returns `adjustedContentInset` on iOS >= 11 and `contentInset` on iOS < 11.
    var fullContentInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return adjustedContentInset
        } else {
            return contentInset
        }
    }

    /// Visible content frame. Equal to bounds without insets.
    var visibleContentFrame: CGRect {
        bounds.inset(by: fullContentInsets)
    }
}

if scrollView.visibleContentFrame.contains(view) {
    // View is fully visible even if there are overlaying views
}
于 2021-11-19T00:36:00.937 回答