change the height of a UICollectionReuseableView (collection section header) dynamically

DirtyKalb picture DirtyKalb · Jan 17, 2013 · Viewed 32.9k times · Source

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;
}

Answer

Ash Furrow picture Ash Furrow · Jan 17, 2013

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.