水平滚动时,如何使UICollectionView在两个单元格的中心对齐?

问题描述

只是想开始说我确实读过this question,但这似乎是为了将一个单元格捕捉到中心。

基本上,我正在寻找:水平滚动时,如何使2个单元格居中时停止?基本上停在2个单元格的中间。

这是我在另一篇文章中所研究的内容,但是我不确定如何使两个居中的单元格(而不是一个居中)工作。

extension UICollectionView {
    func scrollToNearestVisibleCollectionViewCell() {
        self.decelerationRate = UIScrollViewDecelerationRateFast
        let visibleCenterPositionOfScrollView = Float(self.contentOffset.x + (self.bounds.size.width / 2))
        var closestCellIndex = -1
        var closestdistance: Float = .greatestFiniteMagnitude
        for i in 0..<self.visibleCells.count {
            let cell = self.visibleCells[i]
            let cellWidth = cell.bounds.size.width
            let cellCenter = Float(cell.frame.origin.x + cellWidth / 2)

            // Now calculate closest cell
            let distance: Float = fabsf(visibleCenterPositionOfScrollView - cellCenter)
            if distance < closestdistance {
                closestdistance = distance
                closestCellIndex = self.indexPath(for: cell)!.row
            }
        }
        if closestCellIndex != -1 {
            self.scrollToItem(at: IndexPath(row: closestCellIndex,section: 0),at: .centeredHorizontally,animated: true)
        }
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    self.collectionView.scrollToNearestVisibleCollectionViewCell()
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView,willDecelerate decelerate: Bool) {
    if !decelerate {
        self.collectionView.scrollToNearestVisibleCollectionViewCell()
    }
}

要查看我正在谈论的功能类型,请转到Apple Music上的任何艺术家个人资料,然后水平滚动“专辑”部分。它停止完美居中2个单元格!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)