Luke B
Luke B

Reputation: 308

Change cell colour when tapped UICollectionView

I'm working on an app with a UICollectionView, and I use didSelectItemAt to change a boolean's value, but I need to make the cell colour change when I tap on it. This is the didSelectItemAt that I am using:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell

    let caseName = OLLData.list[indexPath.item].image
    print(caseName, OLLData.list[indexPath.item].selected)

    OLLData.list[indexPath.item].selected = !OLLData.list[indexPath.item].selected

    if OLLData.list[indexPath.item].selected == true {
        cell.imageView.backgroundColor = UIColor.yellow
        print("Changed Colour to Yellow")
    }
    else {
        cell.imageView.backgroundColor = UIColor.clear
        print("Changed Colour to Clear")
    }

}

Am I doing this the right way, or is there another?

Upvotes: 0

Views: 53

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100533

Replace

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell

with

let cell = collectionView.cellForItem(at: indexPath) as! PhotoCell

Or better after you apply the changes to the model reload that indexPath

collectionView.reloadItems(at:[indexPath])

dequeueReusableCell shouldn't be used out of cellForItemAt


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell  
    cell.imageView.backgroundColor = OLLData.list[indexPath.item].selected ? UIColor.yellow : UIColor.clear  
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)  {
    let caseName = OLLData.list[indexPath.item].image
    print(caseName, OLLData.list[indexPath.item].selected) 
    OLLData.list[indexPath.item].selected = !OLLData.list[indexPath.item].selected 
    collectionView.reloadItems(at:[indexPath])
}

Upvotes: 2

Related Questions