Skip to content

Instantly share code, notes, and snippets.

@mthongvanh
Last active August 29, 2015 14:10
Show Gist options
  • Save mthongvanh/566043e6483bde016639 to your computer and use it in GitHub Desktop.
Save mthongvanh/566043e6483bde016639 to your computer and use it in GitHub Desktop.
via #iosdev on freenode.net: User wanted the first and last column of a 7-Column collection view to be wider than the middle columns
// Intent: Create a 7-Column collection view where the first and last column are wider than the middle columns
// Solution: Via the UICollectionViewDeleateFlowLayout calculate the correct size of the cells
const NSUInteger daysInWeek = 7;
const CGFloat cellHeight = 54.f;
const CGFloat sizeRatioForWeekStartEnd = 0.20;
const CGFloat sizeRatioForMiddleDays = (1 - (2 * sizeRatioForWeekStartEnd)) / (daysInWeek - 2);
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize cellSize = CGSizeZero;
NSUInteger startOfWeek = 0;
NSUInteger endOfWeek = 6;
NSInteger currentDay = indexPath.row % daysInWeek;
NSUInteger spacerColumns = daysInWeek - 1;
CGFloat totalWidthOfSpacerColumns;
UICollectionViewFlowLayout *flowLayout;
if ([collectionViewLayout isKindOfClass:[UICollectionViewFlowLayout class]]) {
flowLayout = (UICollectionViewFlowLayout*)collectionViewLayout;
totalWidthOfSpacerColumns = spacerColumns * flowLayout.minimumInteritemSpacing;
} else {
#warning Handle this error gracefully in production
NSLog(@"collectionViewLayout should be a UICollectionViewFlowLayout");
abort();
}
CGFloat spaceAvailableForDayCellsInRow = CGRectGetWidth(collectionView.bounds) - totalWidthOfSpacerColumns;
CGFloat cellWidth;
if (currentDay == startOfWeek || currentDay == endOfWeek) {
cellWidth = spaceAvailableForDayCellsInRow * sizeRatioForWeekStartEnd;
} else {
cellWidth = spaceAvailableForDayCellsInRow * sizeRatioForMiddleDays;
}
cellSize.width = cellWidth;
cellSize.height = cellHeight;
return cellSize;
}
@thomasdegry
Copy link

Hey, it worked now, started from scratch! Thanks! And the reason why it was messed up sometimes was of screen sizes, sizeForRationMiddleDays en sizeForRatioWeekStartEnd might be floats, which it ends up rounding, but that makes it possible that there was 2px of free space that messed up the entire layout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment