Murat Kaya Murat Kaya - 1 month ago 13
iOS Question

UICollectionviewCell backgroundColor not Change when selected

I'm trying to change backgorund color of cell when its selected. But cell background color not changing.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CategoryCollectionViewCell
let category = self.categories[indexPath.row]
switch cell.isSelected {
case true:
cell.backgroundColor = .black
default:
cell.backgroundColor = .white
}
cell.setNeedsDisplay()


}

Answer

You don't need to manually change the background color upon selection. UICollectionViewCell has a property called selectedBackgroundView precisely for this purpose.

Use it in your collectionView(_:cellForItemAt:) delegate method as follows:

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

    cell.selectedBackgroundView = UIView(frame: cell.bounds)
    cell.selectedBackgroundView!.backgroundColor = .black

    return cell
}