-1

Hi have a collectionview. Each cell's width is screenwidth/3. Means 3 cells in a row. Now. If have 10 or 11 cells then there will be 4 rows. and there are 1 or 2 cells in last row. The problem is ,I want to align these cell to center without changing its size . now cells are left align.

Note: I want to achieve this with in a section(Because collection-view already have multiple sections). Image attached what i want to achieve .enter image description here

Taimoor Suleman
  • 1,463
  • 11
  • 28

1 Answers1

2

You can solve this using multiple sections. Number of section should be

numberOfSection = totalItemCount/3 > Int(totalItemCount/3) ? Int(totalItemCount/3) + 1 : Int(totalItemCount/3)

dont use ceiling. Then number of items in section should be

numberOfItemInSection = totalItemCount-section*3 < 3 ? totalItemCount-section*3 : 3

Then implement the UICollectionViewDelegateFlowLayout delegate. Where in collectionView(_ collectionView:, layout:, insetForSectionAt:) set,

let minimumInterItemSpacing: CGFloat = 8.0
// minimumInterItemSpacing should be same in the delegate function
let itemCountInSection = collectionView.numberOfItems(inSection: section)
let edgeSpace = (collectionView.bounds.width - ((itemCountInSection*self.itemWidth) + (minimumInterItemSpacing*(itemCountInSection-1)))) / 2
return UIEdgeInsets(top: self.topSpace, left: edgeSpace, bottom: self.bottomSpace, right: edgeSpace)

set other delegate methods as it suits you.