首页 > 解决方案 > 如何判断 CollectionViewCell 是否位于屏幕中心

问题描述

我有一个UICollecitonView水平滚动的。我有一个要求,当用户向右或向左滚动时,屏幕水平中心的集合视图单元格的颜色不同。每次通过中心时,颜色都需要更新。

我们的 UICollectionView 在启动时显示三个UICollectionViewCells,所以“center”定义为第二个的 CGRect UICollectionViewCell

如何检测到这一点?是否有在滚动结束时触发的事件?另外,如何判断一个 CGRect 矩形是否在另一个 CGRect 矩形的边界内?

标签: iosswiftuicollectionview

解决方案


这个答案会让你大致了解 1. 如何获取 scrollView 事件回调。2. 如何将点或矩形从一个视图坐标转换为另一个视图坐标。3.如何在CollectionView中获取CollectionViewCell。

您可以根据需要更改代码。

1.创建一个方法如下

    func scrollViewDidEndScrolling(_ scrollView: UIScrollView) {

         let centerPoint = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.minY)
         let collectionViewCenterPoint = self.view.convert(centerPoint, to: collectionView)    

         if let indexPath = collectionView.indexPathForItem(at: collectionViewCenterPoint) { 
                let collectionViewCell = collectionView.cellForItem(at: indexPath)
                collectionViewCell?.backgroundColor = UIColor.red
         }
    }

在上述方法中,我们试图找到CollectionViewCell位于CollectionView. 我们正在尝试获取它CollectionViewCell的 indexPath 并更新其背景颜色。

2.实现以下给定的ScrollViewDelegate方法

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
         self.scrollViewDidEndScrolling(scrollView)
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

         if !decelerate {
            self.scrollViewDidEndScrolling(scrollView)
         }
    }

我们必须从这些方法中调用我们的ScrollViewDelegate方法。这些方法在collectionView停止滚动时被调用。


推荐阅读