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

时间:2016-07-29 11:26:21

标签: ios swift constraints collectionview

我有一个collectionView,我的滚动视图有一个扩展名,可以帮助我在屏幕右侧获取我的单元格20像素(下一个单元格的最小空间),如下所示:

enter image description here

现在我想更改我的扩展程序,将其集中到容器中,如下所示: enter image description here

我的扩展是这样的:(如果我可以用任何其他方式随意告诉它)

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
    }
}

1 个答案:

答案 0 :(得分:3)

我说

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
)