Last active
November 29, 2016 08:51
-
-
Save giulio92/34062d5479fae0512225aae7c03d8bba to your computer and use it in GitHub Desktop.
Top aligned UICollectionViewCells
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
@implementation CollectionViewFlowLayoutSubclass | |
- (void)awakeFromNib { | |
[super awakeFromNib]; | |
} | |
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { | |
NSArray *attributesToReturn = [super layoutAttributesForElementsInRect:rect]; | |
for (UICollectionViewLayoutAttributes *attributes in attributesToReturn) { | |
if (!attributes.representedElementKind) { | |
attributes.frame = [self layoutAttributesForItemAtIndexPath:attributes.indexPath].frame; | |
} | |
} | |
return attributesToReturn; | |
} | |
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { | |
UICollectionViewLayoutAttributes *currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath]; | |
UIEdgeInsets sectionInset = [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout sectionInset]; | |
if (indexPath.item == 0) { | |
CGRect frame = currentItemAttributes.frame; | |
frame.origin.y = sectionInset.top; | |
currentItemAttributes.frame = frame; | |
return currentItemAttributes; | |
} | |
CGRect previousFrame = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.item - 1 inSection:indexPath.section]].frame; | |
CGRect currentFrame = currentItemAttributes.frame; | |
CGRect strecthedCurrentFrame = CGRectMake(currentFrame.origin.x, 0, currentFrame.size.width, self.collectionView.frame.size.height); | |
if (!CGRectIntersectsRect(previousFrame, strecthedCurrentFrame)) { | |
CGRect frame = currentItemAttributes.frame; | |
frame.origin.y = frame.origin.y = sectionInset.top; | |
currentItemAttributes.frame = frame; | |
return currentItemAttributes; | |
} | |
CGRect frame = currentItemAttributes.frame; | |
frame.origin.y = previousFrame.origin.y + previousFrame.size.height + kVerticalSpacing; | |
currentItemAttributes.frame = frame; | |
return currentItemAttributes; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment