如何以编程方式启用/禁用UICollectionView中的节标题?

如何以编程方式启用/禁用UICollectionView中的节标题?

在Storyboard(checkbox)中可以很容易地完成,但是在代码中如何做呢?

您可以使用UICollectionViewDelegateFlowLayoutcollectionView:layout:referenceSizeForHeaderInSection:方法并返回CGSizeMake(0,0)或者相应地设置UICollectionViewFlowLayoutheaderReferenceSize

编辑: headerReferenceSize实际上是故事板用来显示/隐藏标题的属性。 我已经添加了故事板文件中的相关行

选中部分checkbox:

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

closures部分checkbox

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

编辑#2:

从官方文档 :

stream布局中的每个部分都可以有自己的自定义页眉和页脚。 要为页面或页脚configuration视图,必须将页眉或页脚的大小configuration为非零。 您可以通过实现适当的委托方法或通过将适当的值分配给headerReferenceSize和footerReferenceSize属性来完成此操作。 如果页眉或页脚大小为0,则相应的视图不会添加到集合视图中。

只要将高度更改为0,您不想显示的标题…

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

无论是否和[UIView新]都起作用,都会抛出同样的错误。 最好的答案是如何以编程方式更改UICollectionView footerview的高度

有一个名为“isHidden”的属性,当不需要的时候,它可以用来隐藏节标题。

请参考下面的代码:

 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var reusableView : UICollectionReusableView! if (kind == UICollectionElementKindSectionHeader) { let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderCell", for: indexPath) as! CVHeader let arrayData = summary[indexPath.section] cell.headerLabel.text = arrayData.first as? String if cell.headerLabel.text == "" { cell.isHidden = true //this will hide the header and leave a blank space. } reusableView = cell } if (kind == UICollectionElementKindSectionFooter) { reusableView = nil } return reusableView } 

如果文本为空,上面的代码将隐藏部分标题。 这在xcode8上工作得很好。

当你根本不想要一个头部出现在代表的

 viewForSupplementaryElementOfKind 

只要return [UIView new];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*/ ; }