I'm working on a project that uses an UICollectionView
to show several albums. The items show fine, but now I want to show an header above the first section.
To do this, I added the registerNib:forSupplementaryViewOfKind:withReuseIdentifier:
to my init method. Like this:
[self.collectionView registerNib:[UINib nibWithNibName:@"AlbumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kAlbumHeaderIdentifier];
(The AlbumHeader
Nib contains a view of the class AlbumHeader
, which is a subclass of UICollectionView
.)
After that, I implemented collectionView:viewForSupplementaryElementOfKind:atIndexPath
method:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
return [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kAlbumHeaderIdentifier forIndexPath:indexPath];
}
Now it should try to load the header view, I suppose. But it doesn't, the method for the supplementary view doesn't get called.
What am I missing? Stuck for hours, have read the documentation on UICollectionView
s many times, but nothing seems to help. Any thoughts?
After looking for the method yuf asked about, I read that by default the size of headers/footers are 0,0. If the size is 0, the header/footer won't display.
You can set the size with a property:
Then all the headers will have the same size. If it has to be different for each section, you can implement the following method, which is part of the
UICollectionViewDelegateFlowLayout
protocol.Note that in vertical scrolling it uses the returned
height
and the full width of the collection view, in horizontal scrolling it uses the returnwidth
and the full height of the collection view.for SWIFT 3 & SWIFT 4
You have to add this to ViewDidLoad, and notice the
This will make the header Section Layouts
and Thanks @Guido Hendriks, and all I have got the insight from their answer as well
Did you implement:
There's a ton of methods to implement just to make one thing work...I'm learning too. Tell me if it works.
Edit: Sorry wrong method. That is for subclassing I think. The one I'm talking about is in
UICollectionViewLayout
(the layout object you subclass, if your layout supports supplementary views):See here: https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UICollectionViewLayout_class/Reference/Reference.html#//apple_ref/occ/cl/UICollectionViewLayout