I have a strange problem with collectionView
, I have two prototypes, first one should draw in indexPath.row=0
and the second one should be created four times.
The second prototype contains one UIView for holding an icon that created with paintCode app, and a text label. I have also four icons for each cell.
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch indexPath.row {
case 0:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as? ViewData {
return cell
}
case 1,2,3,4:
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell2", for: indexPath) as? ViewData {
switch indexPath.row {
case 1:
cell.dataIcon.is1stIcon = true
cell.title.text = "1"
case 2:
cell.dataIcon.is2ndIcon = true
cell.title.text = "2"
case 3:
cell.dataIcon.is3rdIcon = true
cell.title.text = "3"
case 4:
cell.dataIcon.is4thIcon = true
cell.title.text = "4"
default:
break
}
return cell
}
default:
break
}
return UICollectionViewCell()
}
The problem is, all text is located in the right place (row), but the 1stIcon
in the indexPath.row=1
will be shown in indexPath.row=3
, and 3rtIcon
will be shown in indexPath.row=1
.
First I thought maybe the problem come from the icons, but whatever I put in these row, has the same wrong tendency.
What do you thing about it?
Thanks
The problem happens as of cell dequeuing you need to re-set everything before using it like
cell.reset()
switch indexPath.row {
case 1:
cell.dataIcon.is1stIcon = true
cell.title.text = "1"
case 2:
cell.dataIcon.is2ndIcon = true
cell.title.text = "2"
case 3:
cell.dataIcon.is3rdIcon = true
cell.title.text = "3"
case 4:
cell.dataIcon.is4thIcon = true
cell.title.text = "4"
default:
break
}
func reset() {
// show all of them
self.dataIcon.is1ndIcon = false
self.dataIcon.is2ndIcon = false
self.dataIcon.is3ndIcon = false
self.dataIcon.is4ndIcon = false
}