Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()    
}
like image 762
Murat Kaya Avatar asked Mar 18 '26 06:03

Murat Kaya


2 Answers

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
}
like image 153
jamesk Avatar answered Mar 19 '26 20:03

jamesk


Try the following in you didSelect delegate method:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let selectedCell = collectionView.cellForItemAtIndexPath(indexPath)

    selectedCell?.backgroundColor = UIColor.blueColor()
}
like image 27
keith Avatar answered Mar 19 '26 18:03

keith