um app
um app

Reputation: 21

Changing the text of a label when a collection view cell is tapped in swift 4.0

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:

Cell

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

Answers (1)

Shehata Gamal
Shehata Gamal

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

Related Questions