ios - 一旦在ios swift中滚动结束,如何在选择中心单元格处触发didSelectItemAtIndexPath?
问题描述
这里UPCarouselFlowLayout用于轮播滚动。截至目前,用户必须点击一个单元格才能触发集合视图 didSelectItemAtIndexPath。一旦滚动自动结束,有没有办法选择中心单元格?
这是我用来轮播的代码:
let layout = UPCarouselFlowLayout()
layout.itemSize = CGSize(width: 211, height: 75)
layout.scrollDirection = .horizontal
layout.spacingMode = UPCarouselFlowLayoutSpacingMode.fixed(spacing: 10)
layout.spacingMode = UPCarouselFlowLayoutSpacingMode.overlap(visibleOffset: 65)
carCollection.collectionViewLayout = layout
这里用于集合视图的代码:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return carCategory.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! carCollectionViewCell
cell.carName.text = carCategory[indexPath.row]
cell.carImage.image = UIImage(named: carCategoryImage[indexPath.row])
cell.carMeters.text = carCategoryMeter[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("selected index::\(indexPath.row)")
}
解决方案
如果您ViewController.swift
从 ** UPCarouselFlowLayout** 附带的 Demo 中查看,您将看到该功能scrollViewDidEndDecelerating
。当滚动停止移动并且一个单元格成为“中心”单元格时触发。
在该函数中,变量currentPage
被设置,这就是集合视图下方的标签被更改的地方。
所以,这是一个尝试你想做的事情的地方。
添加如下所示的两行...当滚动停止时,您创建一个IndexPath
并手动调用didSelectItemAt
:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let layout = self.collectionView.collectionViewLayout as! UPCarouselFlowLayout
let pageSide = (layout.scrollDirection == .horizontal) ? self.pageSize.width : self.pageSize.height
let offset = (layout.scrollDirection == .horizontal) ? scrollView.contentOffset.x : scrollView.contentOffset.y
currentPage = Int(floor((offset - pageSide / 2) / pageSide) + 1)
// add these two lines
let indexPath = IndexPath(item: currentPage, section: 0)
collectionView(self.collectionView, didSelectItemAt: indexPath)
}
您几乎肯定会想要添加一些错误检查和附加功能(例如仅在单元格实际更改时才调用 didSelect,而不是仅将其滑动一点但保留在当前单元格上),但这是一个起点。
推荐阅读
- javascript - 如何仅从图像 url 将图像发送到服务器?
- c - 如何使用 Make 将目标文件编译到存档中
- reactjs - useContext 值未更新
- c - The strtok Function With char * Argument
- javascript - Vue.js 3 中的插槽继承
- python - id="loginbutton" name="login" tabindex="0" type="submit">... 在点 (600, 341) 不可点击。无法点击 Facebook 上的登录按钮
- object - 如何将构造函数的实例分配给变量?
- angular - Angular:数据路径“”不应具有其他属性(entryComponent)
- java - 为什么这个简单的广播接收器不起作用?
- jenkins - Jenkinsfile 一种类型的参数而不是两种类型,将选择转换为字符串或字符串转换为选择