I was working on iOS application and I have several problem about using UICollectionView cell.
This time, I want to ask about how to display the section header of UICollectionView (UICollectionReusableView)
I already implement the function like below :
public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "cellHeader", for: indexPath as IndexPath)
var labelHeader = headerView.viewWithTag(2) as! UILabel
if indexPath.section == 0 {
labelHeader.text = "Specialist Clinic"
}
else {
labelHeader.text = "Medical Support"
}
headerView.backgroundColor = UIColor.blue;
return headerView
default:
assert(false, "Unexpected element kind")
}
}
but, it always give a blank result. please look at the screen shot below
You need to return size of header.
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 123) // you can change sizing here
}
Delegate method
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
var reusableview: UICollectionReusableView? = nil
if kind == UICollectionElementKindSectionHeader {
reusableview = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "cellHeader", for: indexPath) // cellHeader is your identifier
var labelHeader = reusableview.viewWithTag(2) as! UILabel
if indexPath.section == 0 {
labelHeader.text = "Specialist Clinic"
}
else {
labelHeader.text = "Medical Support"
}
headerView.backgroundColor = UIColor.blue;
}
return reusableview!
}