How can I enable/disable section headers in UICollectionView programmatically?

好久不见. 提交于 2019-12-03 09:23:12
spassas

You can either use the collectionView:layout:referenceSizeForHeaderInSection: method of the UICollectionViewDelegateFlowLayout and return CGSizeMake(0,0) or set accordingly the headerReferenceSize of UICollectionViewFlowLayout.

Edit: headerReferenceSize is actually the property that storyboard uses to show/hide the headers. I've added the relevant lines from the Storyboard file

With section checkbox on:

 <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="xAt-Uo-bMl">
           <size key="headerReferenceSize" width="50" height="50"/></collectionViewFlowLayout>

With section checkbox off

 <collectionViewFlowLayout key="collectionViewLayout" minimumLineSpacing="10" minimumInteritemSpacing="10" id="xAt-Uo-bMl">
           <size key="headerReferenceSize" width="0" height="0"/></collectionViewFlowLayout>

Edit #2:

From the official docs:

Each section in a flow layout can have its own custom header and footer. To configure the header or footer for a view, you must configure the size of the header or footer to be non zero. You can do this by implementing the appropriate delegate methods or by assigning appropriate values to the headerReferenceSize and footerReferenceSize properties. If the header or footer size is 0, the corresponding view is not added to the collection view.

MiMo

Just change the height to 0 of the headers you don't want to show...

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeZero;
    }else {
        return CGSizeMake(collectionView.frame.size.width,50);
    }
}
Hammer

Neither nil nor [UIView new] works an both throw the same error. The best answer is in How to change the UICollectionView footerview's height programatically

Afonso Tsukamoto

When you simply don't want an header to appear, in the delegate's

viewForSupplementaryElementOfKind

Just return [UIView new]; when kind == UICollectionElementKindSectionHeader:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{   
    if (kind == UICollectionElementKindSectionHeader) {
       return [UIView new]; // Or even nil, I think it would work.
    }
    ...
    return /*something else that you want to return*/ ;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!