Reputation: 7032
When adding a custom flow layout to a collection view the accessories option go away, Why?, I used this flow layout to center elements of my collection view, but since there's no way to add a section header to my collection view using the storyboard, what are the steps to add a header for the collection view?
What I tried was:
Since my custom layout is a subclass of UICollectionViewFlowLayout, at the storyboard editor I selected the layout (yellow cube) in the left object lister. Then at the Identity Inspector I selected the class of my custom layout.
The collection view seems to create the space for the header, but nothing is displayed inside of it, even if I only ser another background color to the reusable view, it doesn't display anything.
Upvotes: 0
Views: 3843
Reputation: 750
In Objective-C
Call the registerCell method inside the viewDidLoad
- (void)registerCell {
UINib *cellNibTitle = [UINib nibWithNibName:@"YOUR_HEADER_CELL" bundle:nil];
[self.collection registerNib:cellNibTitle forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
}
and call the delegate method:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
if(kind == UICollectionElementKindSectionHeader){
YOUR_HEADER_CELL *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
return headerView;
}
return [UICollectionReusableView new];
}
Upvotes: 0
Reputation: 7032
After some research I found what I was looking for:
I had to create my header in a separate xib, so here's what I did:
Swift 3.2
override func viewDidLoad() {
...
let headerNib = UINib(nibName: "HeaderCollectionReusableView", bundle: nil)
collection.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")
}
viewForSupplementaryElementOfKind
methodSwift 3.2
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath)
return headerView
default://I only needed a header so if not header I return an empty view
return UICollectionReusableView()
}
}
Upvotes: 2