Skip to content

Instantly share code, notes, and snippets.

@MadeByDouglas
Created June 27, 2016 04:40
Show Gist options
  • Save MadeByDouglas/384b4f459bc53e8bd3c0ea4430e1a5d7 to your computer and use it in GitHub Desktop.
Save MadeByDouglas/384b4f459bc53e8bd3c0ea4430e1a5d7 to your computer and use it in GitHub Desktop.
CollectionView Cells fit across screen the easy way
// Use this one and it pulls flowLayout info, even from storyboard
extension UICollectionViewFlowLayout {
func cellsFitAcrossScreen(numberOfCells: Int, labelHeight: CGFloat, cellShapeRatio: CGFloat) -> CGSize {
//using information from flowLayout get proper spacing for cells across entire screen
let insideMargin = self.minimumInteritemSpacing
let outsideMargins = self.sectionInset.left + self.sectionInset.right
let numberOfDivisions: Int = numberOfCells - 1
let subtractionForMargins: CGFloat = insideMargin * CGFloat(numberOfDivisions) + outsideMargins
let fittedWidth = (UIScreen.mainScreen().bounds.width - subtractionForMargins) / CGFloat(numberOfCells)
let ratioHeight = fittedWidth * cellShapeRatio
return CGSize(width: fittedWidth, height: ratioHeight + labelHeight)
}
}
// use this one when you dont have flow layout for whatever reason
static func cellsFitAcrossScreen(numberOfCells: Int, labelHeight: CGFloat, itemSpacing: CGFloat, sectionInsetLeft: CGFloat, sectionInsetRight: CGFloat) -> CGSize {
//using hardwired info get proper spacing for cells across entire screen
let insideMargin = itemSpacing
let outsideMargins = sectionInsetLeft + sectionInsetRight
let numberOfDivisions: Int = numberOfCells - 1
let subtractionForMargins: CGFloat = insideMargin * CGFloat(numberOfDivisions) + outsideMargins
let fittedWidth = (UIScreen.mainScreen().bounds.width - subtractionForMargins) / CGFloat(numberOfCells)
return CGSize(width: fittedWidth, height: fittedWidth + labelHeight)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment