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.