首页 > 解决方案 > 一旦在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)")

}

标签: iosswiftxcodeuicollectionviewcarousel

解决方案


如果您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,而不是仅将其滑动一点但保留在当前单元格上),但这是一个起点。


推荐阅读