Created
January 4, 2017 20:29
-
-
Save natanrolnik/f81d9b0b2c2ee13a09a0b879bf9c0174 to your computer and use it in GitHub Desktop.
Make spacing and section insets equal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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