【问题标题】:How to tell if a CollectionViewCell is at the center of screen如何判断 CollectionViewCell 是否位于屏幕中心
【发布时间】:2018-07-12 17:44:36
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以使用UIScrollViewDelegate 中的scrollViewWillEndDragging:withVelocity:targetContentOffset: 来确定要居中的单元格。
  • 颜色是否需要仅在滚动完成后更新,或者是否需要在每次通过中心时更新?此外,“中心”是定义为单个点 (CGPoint)、范围 (CGRect) 还是恰好离最近点最近的任何单元格?

标签: ios swift uicollectionview


【解决方案1】:

这个答案会让你大致了解 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
         }
    }

在上述方法中,我们试图找到位于CollectionView 中心的CollectionViewCell。我们正在尝试获取 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 停止滚动时被调用。

【讨论】:

  • 谢谢,通过一些小的修改,我能够调整您的代码并完全按照我的需要去做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多