I want have a control of the header of a UICollectionView as I need to remove and add it based on user-generated events.
What I have tried so far:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
if(toRemoveHeader){
return CGSizeZero;
}else{
return CGSizeMake(320, 45);
}
}
And then call [self.collectionView reloadData]
whenever the user-event is generated. I would prefer to make this without reloading the data. Any ideas?
If you are using Swift you can do it this way in your UICollectionViewController
subclass:
var hideHeader: Bool = true //or false to not hide the header
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if hideHeader {
return CGSizeZero //supplementary view will not be displayed if height/width are 0
} else {
return CGSizeMake(30,80) //size of your UICollectionReusableView
}
}
Your implementation is fully functional, the problem might be that you don't assign the object implementing that function to the delegate
property of your collectionView
.
The function collectionView:layout:referenceSizeForHeaderInSection:
is implemented by a class confirming to the UICollectionViewDelegateFlowLayout
protocol, and the collectionView
expects its delegate
to implement this method, and not its dataSource
.
In one of my implementations I show a footer
only if there are no cells in that section
, and as long as the delegate
property is set correctly it works perfectly.
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize) collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForFooterInSection:(NSInteger)section
{
NSUInteger count = [self collectionView: collectionView
numberOfItemsInSection: section];
CGFloat footerHeight = (count == 0) ? 60.f : 0.f;
CGFloat footerWidth = collectionView.frame.size.width;
return CGSizeMake(footerWidth, footerHeight);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With