0

I wanted items of UICollectionView's to be in center so I wrote the following code:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    let collectionViewWidth = collectionView.bounds.width
    let collectionViewHeight = collectionView.bounds.height
    let numberOfRows = CGFloat(collectionView.numberOfItemsInSection(0))
    let leftValue = (collectionViewWidth / 2.0) - (numberOfRows * 5) - (numberOfRows * (collectionViewHeight / 2.0))
    print(leftValue)
    return UIEdgeInsets(top: 0, left: leftValue, bottom: 0, right: 0)
}

But now the problem is I can't scroll it to the left as my left insets changed, Please suggest me any solution.

Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57

1 Answers1

0

I figured this out by doing some calculations and all, so here is the code:

func refreshCollectionView(count: Int) {
    let collectionViewHeight = collectionView.bounds.height
    let collectionViewWidth = collectionView.bounds.width
    let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth / collectionViewHeight)
    if numberOfItemsThatCanInCollectionView > count {
        let totalCellWidth = collectionViewHeight * CGFloat(count)
        let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1)
        // leftInset, rightInset are the global variables which I am passing to the below function
        leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        rightInset = -leftInset
    } else {
        leftInset = 0.0
        rightInset = -collectionViewHeight
    }
    collectionView.reloadData()
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}

For more detailed code you can see my code here https://github.com/anirudha-music/CollectionViewCenter

Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57