Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natanrolnik/f81d9b0b2c2ee13a09a0b879bf9c0174 to your computer and use it in GitHub Desktop.
Save natanrolnik/f81d9b0b2c2ee13a09a0b879bf9c0174 to your computer and use it in GitHub Desktop.
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