I am trying to set the height of the section headers for a UICollectionView
dynamically, but using the code below, I am not seeing anything change. The view is drawn with the correct items in it but the height will not budge. Sorry if this is a repeat question, but I can't seem to find anything related specifically to the UICollectionView
object. Thanks in advance.
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSString *)kind
atIndexPath:(NSIndexPath *)indexPath
{
PhotoVideoHeaderCell *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:@"videoHeaderView"
forIndexPath:indexPath];
if (indexPath.section == 0) {
// photos
[headerView setSection:@"Photo"];
} else {
[headerView.VehicleDetailView removeFromSuperview];
CGRect frame = headerView.frame;
frame.size.height = 60;
[headerView setFrame:frame];
[headerView setNeedsDisplay];
[headerView setBackgroundColor:[UIColor grayColor]];
[headerView setSection:@"Video"];
}
return headerView;
}
Make-CollectionView-Height-Dynamic-According-to-ContentAdd a height constraint to your collection view. Set its priority to 999. Set its constant to any value that only makes it reasonably visible on the storyboard. Change the bottom equal constraint of the collection view to greater or equal.
To display this section header, you'll use UICollectionReusableView . This class is like UICollectionViewCell , except it's usually used to display headers and footers. Like cells, UICollectionView places them in a reuse queue rather than deleting them when they scroll out of the visible bounds.
collectionView(_:viewForSupplementaryElementOfKind:at:)Asks your data source object to provide a supplementary view to display in the collection view.
Your delegate should implement the following function, assuming you're using a flow layout:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
You can return a different size for each header. In horizontally scrolling collection views, only the width is used. In vertically scrolling ones, only the height is used. The unused value is ignored — your view will always be stretched to fill the full height/width of horizontal/vertical collection views, respectively.
There is a corresponding method for footers, too.
Accepted answer in Swift 3 and 4:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 250)
}
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