每次滚动视图结束时,将 collectionView 的单元格居中

Center the cell of a collectionView everytime the scrollview ends

我有一个 collectionView 并且我有一个滚动视图的扩展,它可以帮助我在屏幕右侧获得我的单元格 20 像素(距离下一个单元格的最小值 space),如下所示:

现在我想更改我的扩展以将其居中放置在容器中,如下所示:

我的分机是这样的:(如果我能用任何其他方式做,请随意告诉它)

extension MyProject : UIScrollViewDelegate
{
    func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
    {
        let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        let cellWidthIncludingSpacing = layout.itemSize.width + layout.minimumLineSpacing

        var offset = targetContentOffset.memory
        let index = (offset.x + scrollView.contentInset.left) / cellWidthIncludingSpacing
        let roundedIndex = round(index)

        offset = CGPoint(x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left, y: -scrollView.contentInset.top)
        targetContentOffset.memory = offset
    }
}

我会说

offset = CGPoint(
  x: roundedIndex * cellWidthIncludingSpacing - scrollView.contentInset.left + cellWithIncludingSpacing / 2 - scrollView.bounds.size.width / 2,
  y: -scrollView.contentInset.top
)

或者,考虑contentInset更好

let visibleWidth = scrollView.bounds.size.width
  - scrollView.contentInset.left
  - scrollView.contentInset.right
offset = CGPoint(
  x: roundedIndex * cellWidthIncludingSpacing
    - scrollView.contentInset.left
    + layout.itemSize.width / 2
    - visibleWidth / 2,
  y: -scrollView.contentInset.top
)