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()
}
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
}
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With