Last active
February 8, 2023 12:52
-
-
Save mikevoyt/4613982 to your computer and use it in GitHub Desktop.
Example of how to create a pinned header with UICollectionView (i.e., a header that doesn't scroll with the rest of the cells).
As simple as possible - assumes a single header, at index path [0,0], to be pinned at the top of the collection view.
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
//Override UICollectionViewFlowLayout class | |
@interface FixedHeaderLayout : UICollectionViewFlowLayout | |
@end | |
@implementation FixedHeaderLayout | |
//Override shouldInvalidateLayoutForBoundsChange to require a layout update when we scroll | |
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { | |
return YES; | |
} | |
//Override layoutAttributesForElementsInRect to provide layout attributes with a fixed origin for the header | |
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect { | |
NSMutableArray *result = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; | |
//see if there's already a header attributes object in the results; if so, remove it | |
NSArray *attrKinds = [result valueForKeyPath:@"representedElementKind"]; | |
NSUInteger headerIndex = [attrKinds indexOfObject:UICollectionElementKindSectionHeader]; | |
if (headerIndex != NSNotFound) { | |
[result removeObjectAtIndex:headerIndex]; | |
} | |
CGPoint const contentOffset = self.collectionView.contentOffset; | |
CGSize headerSize = self.headerReferenceSize; | |
//create new layout attributes for header | |
UICollectionViewLayoutAttributes *newHeaderAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]]; | |
CGRect frame = CGRectMake(0, contentOffset.y, headerSize.width, headerSize.height); //offset y by the amount scrolled | |
newHeaderAttributes.frame = frame; | |
newHeaderAttributes.zIndex = 1024; | |
[result addObject:newHeaderAttributes]; | |
return result; | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Didn't knew I had to put
layoutAttributesForSupplementaryViewOfKind
inside the call oflayoutAttributesForElementsInRect:(CGRect)rect
.This has been a lot of help. Thanks!