ios - 如何判断 CollectionViewCell 是否位于屏幕中心
问题描述
我有一个UICollecitonView
水平滚动的。我有一个要求,当用户向右或向左滚动时,屏幕水平中心的集合视图单元格的颜色不同。每次通过中心时,颜色都需要更新。
我们的 UICollectionView 在启动时显示三个UICollectionViewCell
s,所以“center”定义为第二个的 CGRect UICollectionViewCell
。
如何检测到这一点?是否有在滚动结束时触发的事件?另外,如何判断一个 CGRect 矩形是否在另一个 CGRect 矩形的边界内?
解决方案
这个答案会让你大致了解 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
停止滚动时被调用。
推荐阅读
- python - 如何解释绘图结果普通岭回归(检查编辑)
- python - 为什么我的 list.append 没有永久添加我的项目?
- javascript - 反应原生元素复选框
- python - 如何在python中逐个字符地将字符串与列表中的项目进行比较
- swift - 进度条不会异步更改
- javascript - 在 Vue.js 中接收到 firebase 数据后调用函数
- c# - 如果方法当前正在运行,则设置属性
- android - ?attr/colorPrimary 在可绘制结果中没有颜色棒棒糖
- html - 使用 css 在悬停选择器(图像标签)上显示多个 div
- docker - 使用 GMSA 通过 Docker IIS 进行 Windows 身份验证