Changing cell background color in UICollectionView in Swift

You can use the function collectionView with the parameter didSelectItemAtIndexPath

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath 
   indexPath: NSIndexPath) {

       let selectedCell:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
       selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
}

This creates a constant for the selected UICollectionViewCell, then you just change the background’s color


And then for return to the original color when it is deselected, you must use the function collectionView with the parameter didDeselectItemAtIndexPath

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cellToDeselect:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
        cellToDeselect.contentView.backgroundColor = UIColor.clearColor()
}

And you change the color to the original one!


For example here is the screenshot from this code in a filterApp

UICollectionView example

Leave a Comment