Last active
August 29, 2015 14:06
-
-
Save jellybeansoup/55e8a2b57c0d22059abf to your computer and use it in GitHub Desktop.
Grid cell size calculator.
This file contains hidden or 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
// Get the view's actual pixel width | |
CGFloat pixelWidth = self.collectionView.frame.size.width * UIScreen.mainScreen.scale; | |
// Maximum cells per row | |
CGFloat maxCells = ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) ? 10.0 : 5.0; | |
// Determine a cell width | |
CGFloat cellWidth = 0.0; | |
CGFloat cellSpacing = 2.0; | |
for( CGFloat i = cellSpacing; i <= 4; i++ ) { | |
// Reset the cells per row | |
CGFloat cellsPerRow = 4.0; | |
// Find an appropriate number of cells per row | |
while( fmodf( ( pixelWidth - ( i * ( cellsPerRow - 1 ) ) ), cellsPerRow ) != 0 ) { | |
// Iterate the number of cells | |
cellsPerRow++; | |
// Break out if it gets stupid | |
if( cellsPerRow > maxCells ) { | |
break; | |
} | |
} | |
// Eureka! We've got it! | |
if( cellsPerRow < maxCells ) { | |
cellWidth = ( ( pixelWidth - ( i * ( cellsPerRow - 1 ) ) ) / cellsPerRow ) / UIScreen.mainScreen.scale; | |
cellSpacing = i / UIScreen.mainScreen.scale; | |
break; | |
} | |
} | |
// Fix this size business | |
self.collectionViewLayout.itemSize = CGSizeMake( cellWidth, cellWidth ); | |
self.collectionViewLayout.minimumLineSpacing = cellSpacing; | |
self.collectionViewLayout.minimumInteritemSpacing = cellSpacing; |
This file contains hidden or 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
// Determine the correct size | |
CGFloat size; | |
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) { | |
size = UIInterfaceOrientationIsLandscape( [[UIApplication sharedApplication] statusBarOrientation] ) ? 169 : 152; | |
} | |
else { | |
size = ( UIScreen.mainScreen.scale == 2.0 ) ? 78.5 : 78; | |
} | |
// Apply the size and cell spacing | |
CGFloat max = floorf( self.view.frame.size.width / size ); | |
self.collectionViewLayout.itemSize = CGSizeMake( size, size ); | |
self.collectionViewLayout.minimumLineSpacing = ( ( self.view.frame.size.width - ( max * size ) ) / ( max - 1 ) ); | |
self.collectionViewLayout.minimumInteritemSpacing = ( ( self.view.frame.size.width - ( max * size ) ) / ( max - 1 ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original code was designed to output 4 cells on iPhone/iPod touch, 5 cells on a portrait iPad, and 6 cells on a landscape iPad.
The new code replicates the results, but isn't tied to a specific screen size.