To add the custom label above every section in UICollectionView, please follow below steps
- Enable the section header in UICollectionView
- Add a new file of type UICollectionReusableView
- In the storyboard change the class of section header in UICollectionViewCell to the newly added file of type UICollectionReusableView.
- Add a label in section header of UICollectionViewCell in storyboard
-
Connect the label in the section header to the UICollectionReusableView file
class SectionHeader: UICollectionReusableView { @IBOutlet weak var sectionHeaderlabel: UILabel! }
-
In the ViewController add the below code
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() }
Here “SectionHeader” is name of the file added to type UICollectionReusableView