Skip to content

Commit 6e7bd0a

Browse files
committed
enable sticky header
chiahsien#188
1 parent e453486 commit 6e7bd0a

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

CHTCollectionViewWaterfallLayout.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ extern NSString *const CHTCollectionElementKindSectionFooter;
297297
*/
298298
@property (nonatomic, assign) UIEdgeInsets sectionInset;
299299

300+
@property (nonatomic, assign) BOOL enableStickyHeader;
300301
/**
301302
* @brief The direction in which items will be rendered in subsequent rows.
302303
* @discussion

CHTCollectionViewWaterfallLayout.m

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,27 @@ - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
464464
}
465465
}
466466
}
467+
if (self.enableStickyHeader) {
468+
for (int i = 0; i < self.allItemAttributes.count; i++) {
469+
UICollectionViewLayoutAttributes *attr = self.allItemAttributes[i];
470+
if ([attr.representedElementKind isEqualToString:CHTCollectionElementKindSectionHeader]) {
471+
NSInteger section = attr.indexPath.section;
472+
NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:section];
473+
NSIndexPath *firstCellIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
474+
NSIndexPath *lastCellIndexPath = [NSIndexPath indexPathForItem:MAX(0, numberOfItemsInSection - 1) inSection:section];
475+
UICollectionViewLayoutAttributes *firstCellAttributes = [self layoutAttributesForItemAtIndexPath:firstCellIndexPath];
476+
UICollectionViewLayoutAttributes *lastCellAttributes = [self layoutAttributesForItemAtIndexPath:lastCellIndexPath];
477+
CGFloat headerHeight = CGRectGetHeight(attr.frame);
478+
CGPoint origin = attr.frame.origin;
479+
CGFloat y1 = MAX(self.collectionView.contentOffset.y, (CGRectGetMinY(firstCellAttributes.frame) - headerHeight));
480+
CGFloat y2 = CGRectGetMaxY(lastCellAttributes.frame) - headerHeight;
481+
origin.y = MIN(y1, y2);
482+
attr.zIndex = 1024;
483+
attr.frame = CGRectMake(origin.x, origin.y, CGRectGetWidth(attr.frame), CGRectGetHeight(attr.frame));
484+
supplHeaderAttrDict[attr.indexPath] = attr;
485+
}
486+
}
487+
}
467488

468489
NSArray *result = [cellAttrDict.allValues arrayByAddingObjectsFromArray:supplHeaderAttrDict.allValues];
469490
result = [result arrayByAddingObjectsFromArray:supplFooterAttrDict.allValues];
@@ -472,6 +493,9 @@ - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
472493
}
473494

474495
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
496+
if (self.enableStickyHeader) {
497+
return YES;
498+
}
475499
CGRect oldBounds = self.collectionView.bounds;
476500
if (CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds)) {
477501
return YES;

0 commit comments

Comments
 (0)