Last active
August 29, 2015 14:10
-
-
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
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
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.