Answer for Objective-C
and Swift2.0
: How to center align the cells of a UICollectionView?
I usually would try to conver
Here's a recent solution, works for Swift 5.0
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
let itemWidth = 80
let spacingWidth = 4
let numberOfItems = collectionView.numberOfItems(inSection: section)
let cellSpacingWidth = numberOfItem * spacingWidth
let totalCellWidth = numberOfItems * itemWidth + cellSpacingWidth
let inset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth)) / 2
return UIEdgeInsets(top: 5, left: inset, bottom: 5, right: inset)
}
}