如何在UICollectionView中添加节标题?

我需要在我的集合视图的每个部分上面有一个标签。 我试过简单地将一个标签拖到我的原型单元格上方的标题空间中,但每次运行应用程序时,标签都不可见。

任何帮助?

实现collectionView:viewForSupplementaryElementOfKind:atIndexPath:并提供一个包含标签的出队UICollectionElementKindSectionHeader。 如果这是一个stream布局,一定要设置headerReferenceSize否则你将看不到任何东西。

从@ david72的答案

您需要执行以下操作:

  1. 在Storyboard中启用节标题/页脚视图。
  2. 实现collectionView:viewForSupplementaryElementOfKind方法。

欲了解更多详情请参阅这里

要在UICollectionView的每个部分上添加自定义标签,请按照以下步骤操作

  1. 在UICollectionViewCell中启用节标题

在这里输入图像说明

  1. 添加一个types为UICollectionReusableView的新文件
  2. 在故事板中,将UICollectionViewCell中的节标题类更改为新添加的UICollectionReusableViewtypes的文件。
  3. 在故事板中的UICollectionViewCell的节头中添加一个标签
  4. 将节标题中的标签连接到UICollectionReusableView文件

     class SectionHeader: UICollectionReusableView { @IBOutlet weak var sectionHeaderlabel: UILabel! } 
  5. 在ViewController中添加下面的代码

     func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeader", for: indexPath) as? SectionHeader{ sectionHeader.sectionHeaderlabel.text = "Section \(indexPath.section)" return sectionHeader } return UICollectionReusableView() } 

这里“SectionHeader”是添加到UICollectionReusableViewtypes的文件的名称