检查UIView是否处于UIScrollView可见状态

问题描述 投票:0回答:8

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

iphone objective-c ios ipad
8个回答
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
    }

23
投票

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

extension ViewController: UIScrollViewDelegate {

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

}

8
投票

在滚动视图委托中实现

scrollViewDidScroll:
并手动计算哪些视图可见(例如,通过检查
CGRectIntersectsRect(scrollView.bounds, subview.frame)
是否返回 true。


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
    }

3
投票

何塞的解决方案对我来说不太有效,它是在我的视图出现在屏幕上之前检测它。如果 José 的更简单的解决方案不适合您,下面的相交代码在我的表格视图中可以完美工作。

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

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
}

2
投票

考虑插图的解决方案

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
}

0
投票

一旦屏幕出现,我们的scrollViewDidScroll委托就会被调用,并且滚动视图内的所有视图相交检查将返回true,因此添加一行 在我们的视图相交检查之前进行scrollView.isTracking。像这样的东西对我有用。

funcscrollViewDidScroll(_scrollView:UIScrollView){

    if scrollView.isTracking {
        let viewFrame1 = scrollView.convert(targetView.bounds, from: targetView)
        
        if viewFrame1.intersects(scrollView.bounds) {
            //Your Methods Goes Here
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.