I want to set up the collection view's header, and thus implemented the method func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
.
However, it seems that the switch statement does not work; even when I tried to set the label within the header view by branching off depending on the section, the resultant header view in all the sections has all the labels I wrote.
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "Header", forIndexPath: indexPath)
let headerLabel = UILabel(frame: CGRectMake(2, 8, 120, 24))
headerView.addSubview(headerLabel)
print(indexPath.section)
switch (indexPath.section) {
case 0:
headerLabel.text = "A"
return headerView
case 1:
headerLabel.text = "B"
return headerView
default:
break
}
return headerView
default:
assert(false, "Unexpected element kind")
}
}
In the above code, the both sections' label has both the label A and B, overlapped each other.
Why does the switch not work in my case?
The contents in my collection view fetch data from the server, and thus the print(indexPath.section)
is executed 2 times, each printing out 0
and 1
, in that order.
Is this related to the problem?