import UIKit
class CenteredFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let superAttributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
guard let collectionView = collectionView else {
return superAttributes
}
let contentWidth = collectionViewContentSize.width
let insetX = max((collectionView.bounds.width - contentWidth) * 0.5, 0.0)
var updatedAttributes = [UICollectionViewLayoutAttributes]()
for attributes in superAttributes {
if attributes.representedElementCategory == .cell {
var updatedFrame = attributes.frame
updatedFrame.origin.x += insetX
attributes.frame = updatedFrame
}
updatedAttributes.append(attributes)
}
return updatedAttributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
let centeredFlowLayout = CenteredFlowLayout()
collectionView.collectionViewLayout = centeredFlowLayout