Search code examples
iosswiftconstraintscollectionview

Center the cell of a collectionView everytime the scrollview ends


I have a collectionView and I have an extension for its scrollview that helps me to get my cell 20pixels(the minimum space from the next cell) right of the screen like this:

enter image description here

now I want to change my extension to center it to the container like this: enter image description here

my extension is this: (if I can do with any other way feel free to tell it)

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

Solution

  • I'd say

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

    or, to consider contentInset better

    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
    )