CollectionView单元格在水平滚动之后移动到右侧

我有一个与我的CollectionView的大小相同的collectionView单元格,即一次显示一个单元格,我希望单元格之间的最小间隔为10,问题是当我滚动单元格时,单元格没有正确安装整个屏幕,并在每次滚动后增加单元格的移动。 (检查屏幕截图以便更好地理解)

这是第三个单元格

这是第六个单元格

在这里输入图像说明

我假设你已经设置了集合视图的pagingEnabled 。 它从UIScrollViewinheritance这个属性(因为UICollectionViewUIScrollView的子类)。

问题是收集视图使用自己的宽度(您的文章中的320点)作为页面的宽度。 每个单元格的宽度与集合视图的宽度相同,但是在单元格之间有一个10点的“装订线”。 这意味着从单元格0的左边缘到单元格1的左边缘的距离是320 + 10 = 330点。 因此,当您滚动显示单元格1时,集合视图停止在偏移量320(其自身宽度)滚动,但单元格1实际上从偏移量330开始。

最简单的解决方法是closurespagingEnabled并通过在您的集合视图委托中覆盖scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)来实现自己的分页,如下所示:

 override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return } let pageWidth = scrollView.bounds.size.width + flowLayout.minimumInteritemSpacing let currentPageNumber = round(scrollView.contentOffset.x / pageWidth) let maxPageNumber = CGFloat(collectionView?.numberOfItems(inSection: 0) ?? 0) // Don't turn more than one more page when decelerating, and don't go beyond the first or last page. var pageNumber = round(targetContentOffset.pointee.x / pageWidth) pageNumber = max(0, currentPageNumber - 1, pageNumber) pageNumber = min(maxPageNumber, currentPageNumber + 1, pageNumber) targetContentOffset.pointee.x = pageNumber * pageWidth } 

您还需要将项目大小设置为与设备屏幕大小相匹配,并将减速率设置为快速:

 override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout, let collectionView = collectionView else { return } flowLayout.itemSize = collectionView.bounds.size collectionView.decelerationRate = UIScrollViewDecelerationRateFast } 

结果:

演示

原因在于,在设置单元格宽度(320)的时候,您没有采用minimum separation of 10 。 因此,这个10每次都会累积起来进行滚动。

所以你必须在设置宽度时减去320中的10,所以宽度应该是310 IMO。