Removing empty space, if the section header is hidden in the UICollectionView

At last, I found an answer for my question. I have missed something. Anyway sorry for other fellow users.

I set the header height and width inside the below method till now as @san said.

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

But It is not the correct method to set the frame size of supplementary views. Later I found another method inside the flowLayout, which helps me to set the header and footer sizes.

This really works well for me:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeZero;
    }else {
        return CGSizeMake(CGRectGetWidth(collectionView.bounds), 135);
    }
}

UPDATE: Since someone questioned about my skill in comments, attaching Apple Documentation link for returning CGSizeZero in above method.


The documentation for collectionView:viewForSupplementaryElementOfKind:atIndexPath: states:

This method must always return a valid view object. If you do not want a supplementary view in a particular case, your layout object should not create the attributes for that view. Alternatively, you can hide views by setting the hidden property of the corresponding attributes to YES or set the alpha property of the attributes to 0. To hide header and footer views in a flow layout, you can also set the width and height of those views to 0.

Considering you have already tried setting the height to zero and setting the view to be hidden, you should subclass UICollectionViewFlowLayout and implement layoutAttributesForSupplementaryViewOfKind:atIndexPath:

Check the indexPath (as you already do) and return nil if you don't want any layout attributes for that specific supplementary view.

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath section] == 0)
    {
         return nil;
    }

    return [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
}