Skip to content

Instantly share code, notes, and snippets.

@ddonovan
Created December 3, 2014 06:26
Show Gist options
  • Save ddonovan/50117cf335c00222e0c9 to your computer and use it in GitHub Desktop.
Save ddonovan/50117cf335c00222e0c9 to your computer and use it in GitHub Desktop.
Calculate a cell size for flowlayout in uicollectionview , assuming you want square cells and have 1pt spacing all around.
- (void)viewWillLayoutSubviews;
{
[super viewWillLayoutSubviews];
UICollectionViewFlowLayout *flowLayout = (id)self.collectionViewLayout;
// really should get this value from the Photo class, but for now max thumb of 110px.
CGFloat cellSize = [self calculateCellSizeForMaxImageWidth:110];
flowLayout.itemSize = CGSizeMake(cellSize, cellSize);
}
- (CGFloat)calculateCellSizeForMaxImageWidth: (NSInteger)maxWidth{
UIScreen *mainScreen = [UIScreen mainScreen];
NSInteger numCells = ceil(mainScreen.bounds.size.width/maxWidth);
NSLog(@"Recommended number of columns %li", (long)numCells);
// this assumes 1pt spacing, insets and cells.
CGFloat cellSize = (mainScreen.bounds.size.width -(numCells+1))/numCells;
NSLog(@"Recommended cell size %f", cellSize);
return cellSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment