Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamesrochabrun/cfc48167d3e10768fec880a2a393022c to your computer and use it in GitHub Desktop.
Save jamesrochabrun/cfc48167d3e10768fec880a2a393022c to your computer and use it in GitHub Desktop.
extension UICollectionView {
func dynamicGrid(numbersOfSquares :Float) -> (rows: Float, columns: Float, cellSize: CGSize) {
let ratio: Float = Float(self.frame.size.width / self.frame.size.height)
let numberOfColumns = sqrt(numbersOfSquares * ratio)
let numberOfRows = numbersOfSquares / numberOfColumns;
// Find best option filling the whole height
var nrows1 = ceil(numberOfRows)
var ncols1 = ceil(numbersOfSquares / nrows1)
while (nrows1 * ratio < ncols1) {
nrows1 += 1
ncols1 = ceil(numbersOfSquares / nrows1)
}
let cellSize1 = Float(self.frame.size.height) / nrows1
// Find best option filling the whole width
var ncols2 = ceil(numberOfColumns)
var nrows2 = ceil(numbersOfSquares / ncols2)
while (ncols2 < nrows2 * ratio) {
ncols2 += 1
nrows2 = ceil(numbersOfSquares / ncols2)
}
let cellSize2 = Float(self.frame.size.width) / ncols2
// Find the best values
var nrows: Float = 0
var ncols: Float = 0
var cellSize: Float = 0
if (cellSize1 < cellSize2) {
nrows = nrows2
ncols = ncols2
cellSize = cellSize2
} else {
nrows = nrows1
ncols = ncols1
cellSize = cellSize1
}
return (rows: nrows, columns: ncols, cellSize: CGSize(width: Double(cellSize), height: Double(cellSize)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment