I added different text labels to my collectionview headers for each section in swift.I use uireusableviews for headers. My problem is when I scroll the text in the labels of different sections overlap with each other.I tried setting the text label to "" before changing the text but the problem still persists.
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if(kind == UICollectionView.elementKindSectionHeader){
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "h", for: indexPath) as? UICollectionViewCell
let txtlab = UILabel()
txtlab.text = ""
if(indexPath.section%2 == 0){
txtlab.text = "Header"}
else{
txtlab.text = "another header"
}
cell?.addSubview(txtlab)
txtlab.translatesAutoresizingMaskIntoConstraints = false
txtlab.centerYAnchor.constraint(equalTo: cell!.centerYAnchor).isActive = true
txtlab.centerXAnchor.constraint(equalTo: cell!.centerXAnchor).isActive = true
cell?.backgroundColor = .green
return cell!
}
You need to clear the views before you generate the new ones.
Put this your method that creates the header at the top.
for view in myView {
myView.removeFromSuperview()
}
Edit, I didn’t see your code.
Your first issue is that you’re creating a new label for every cell. You should create a outlet so that each cell is hooked up to the label. Then you should be able to change the header.