I want my sections in the UICollectionView
to have a header with an image.
I have followed these steps:
You answered the question, but in words I understand better:
To make the method being called, add these methods:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
return CGSizeMake(60.0f, 30.0f);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
return CGSizeMake(60.0f, 30.0f);
}
...and go from there.
I have the same issue. I have added referenceSizeForFooterInSection
but then also viewForSupplementaryElementOfKind
not getting called.
I have added this code in viewDidLoad()
and it worked for me:
if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.sectionFootersPinToVisibleBounds = true
}
Swift 3.0 (xcode 8.2.1)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width:collectionView.frame.size.width, height:30.0)
}
It seems that you have to give your header a non-zero size or collectionView:viewForSupplementaryElementOfKind:atIndexPath
isn't called. So either set the headerReferenceSize
property of the flow layout like so:
flowLayout.headerReferenceSize = CGSizeMake(self.collectionView.frame.size.width, 100.f);
Swift 5+
flowLayout.headerReferenceSize = CGSize(CGSize(width: self.collectionView.frame.size.width, height: 100))
or, implement collectionView:layout:referenceSizeForHeaderInSection
if you want to vary the size by section.
@objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { }
The above code worked for me
Swift 4 Xcode 9.1 Beta 2
Add @objc
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
let size = CGSize(width: 400, height: 50)
return size
}
Credits: https://medium.com/@zonble/your-delegation-methods-might-not-be-called-in-swift-3-c6065ed7b4cd