Answer for Objective-C
and Swift2.0
: How to center align the cells of a UICollectionView?
I usually would try to conver
You need to conform to UICollectionViewDelegateFlowLayout
protocol to find the collectionView(_:layout:insetForSectionAt:)
method, it is defined there. the following implementation works fine in swift 4 for a horizontal collectionView
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let cellWidth = CGFloat(integerLiteral: YourCellsWidth)
let count = self.YourCollectionViewDataSource.count
let top = CGFloat(integerLiteral: 0) // I don't need to set top and bottom spacing
let cellsAccumulatedWidth = CGFloat(integerLiteral: count) * cellWidth
let cellsSpacingAccumulatedWidth = CGFloat(integerLiteral: (count - 1) * 5)
let left = (self.collectionView.frame.size.width - cellsAccumulatedWidth - cellsSpacingAccumulatedWidth) / 2
let bottom = top
let right = left
return UIEdgeInsetsMake(top, left, bottom, right);
}
}