Created
May 12, 2018 22:06
-
-
Save jamesrochabrun/cfc48167d3e10768fec880a2a393022c to your computer and use it in GitHub Desktop.
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
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