Reputation: 21
I am having a problem with changing the text of a label when a collection view cell is tapped. I have tried using didSelectItemAt
and didHighlightItemAt
but nothing worked. Here's what my cell looks like:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.subjectName.text = "Selected"
}
Upvotes: 0
Views: 2257
Reputation: 100541
You need
let cell = collectionview.cellForItem(at: indexPath) as! CollectionViewCell
cell.subjectName.text = "Selected"
but note because of cell dequeuing this change is temporary when the cell is still shown if you scroll around you may find another text inside that index , so reflect the changes in the array model of the collection and reload that indexPath
var statesArr = ["Selected","Default",,,,,,,,,,]
inside didSelectItemAt
statesArr[indexPath.row] = "Selected"
self.collectionView.reloadItems(at:[indexPath])
inside cellForItemAt
let cell = ///
cell.subjectName.text = statesArr[indexPath.row]
Upvotes: 2