I need a label above every section in my Collection View. I\'ve tried simply dragging a label into my header space above my prototype cell, but every time I run the app, the
To add the custom label above every section in UICollectionView, please follow below steps
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