Reputation: 2027
I am attempting to highlight the background of a cell when a user selects it. I have been successful in changing the border of a cell when a user selects it.
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
addToList.append(objectsArray[indexPath.row])
let cell = collectionView.cellForItem(at: indexPath)
cell?.contentView.layer.borderWidth = 2.0
cell?.contentView.layer.borderColor = UIColor.gray.cgColor
}
I have not been able to change the background though.
Can this be done? Thanks!
Upvotes: 1
Views: 181
Reputation: 3494
For cell border, use cell
contentView
like this:
cell?.contentView.layer.borderWidth = 2.0
cell?.contentView.layer.borderColor = UIColor.gray.cgColor
And for cell backgroundColor
color you need to use:
cell?.backgroundColor = .gray
Upvotes: 1
Reputation: 4552
Try this.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell.contentView.backgroundColor = UIColor.red
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell.contentView.backgroundColor = UIColor.white
}
Upvotes: 1