gpt4 book ai didi

ios - 如何判断 CollectionViewCell 是否位于屏幕中央

转载 作者:可可西里 更新时间:2023-11-01 00:39:01 36 4
gpt4 key购买 nike

我有一个水平滚动的 UICollecitonView。我有一个要求,当用户向右或向左滚动时,屏幕水平中心的 Collection View 单元格的颜色不同。颜色需要在每个穿过中心时更新。

我们的 UICollectionView 在启动时显示了三个 UICollectionViewCell,因此“中心”被定义为第二个 UICollectionViewCell 的 CGRect。

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

最佳答案

This answer will give you rough idea about 1. how to get scrollView event callback. 2. how to convert point or rect from one view coordinates to another view coordinates. 3. how to get CollectionViewCell at certain point in CollectionView.

You can change the code as per your requirement.

<强>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 停止滚动时调用这些方法。

关于ios - 如何判断 CollectionViewCell 是否位于屏幕中央,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51311638/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com