我有一个UICollecitonView
,它可以水平滚动。我有一个要求,即当用户向右或向左滚动时,屏幕水平中心的集合视图单元格的颜色会有所不同。当每种颜色穿过中心时,颜色都需要更新。
我们的UICollectionView在启动时显示了三个UICollectionViewCell
,因此将“中心”定义为第二个UICollectionViewCell
的CGRect。
如何检测到这一点?滚动端是否会触发事件?另外,如何判断CGRect矩形是否在另一个CGRect矩形的边界内?
答案 0 :(得分:2)
此答案将使您大致了解 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
停止滚动时,将调用这些方法。