Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make spacing and section insets equal
import UIKit
extension UICollectionViewFlowLayout {
func equalizeSpacing(with minimumSpacing: CGFloat, aItemSize: CGSize? = nil, sectionInsetTop: CGFloat = 0, sectionInsetBottom: CGFloat = 0) {
guard let collectionView = collectionView else { return }
let totalWidth = collectionView.frame.width
let itemSizeToUse = aItemSize ?? itemSize
itemSize = itemSizeToUse
func columnsFit(with numberOfColumns: Int) -> Bool {
let cellsWidth = CGFloat(numberOfColumns) * itemSize.width
let spacingWidth = CGFloat(numberOfColumns + 1) * minimumSpacing
return (cellsWidth + spacingWidth) < totalWidth
}
var columns = 1
while columnsFit(with: columns) {
let newPossible = columns + 1
if columnsFit(with: newPossible) {
columns = newPossible
}
else {
break
}
}
let cellsWidth = CGFloat(columns) * itemSize.width
let spacing = CGFloat(totalWidth - cellsWidth) / CGFloat(columns + 1)
minimumInteritemSpacing = spacing
sectionInset = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: spacing)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.