Skip to content

Instantly share code, notes, and snippets.

@giulio92
Last active November 29, 2016 08:51
Show Gist options
  • Save giulio92/34062d5479fae0512225aae7c03d8bba to your computer and use it in GitHub Desktop.
Save giulio92/34062d5479fae0512225aae7c03d8bba to your computer and use it in GitHub Desktop.
Top aligned UICollectionViewCells
@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