Search code examples
iosswiftuicollectionviewuicollectionviewcell

how to change cell background colour on selected item in UICollectionView and change other Cell colour to default in swift


I am new in swift and I am trying to change cell background colour of UICollectionView but its not working my code is like this in cellForItemAt

if(cell.isSelected){
    cell.backgroundColor = UIColor.green
    }else{
       cell.backgroundColor = UIColor.clear
 }

Is there is any way to change only selected cell colour to green and other cell to clear Thanks in Advance!


Solution

  • Create a variable inside the vc

    var currentSelected:Int?
    

    then inside cellForItemAt

    cell.backgroundColor = currentSelected == indexPath.row ? UIColor.green : UIColor.clear
    

    finally didSelectItemAt

    currentSelected = indexPath.row
    collectionView.reloadData()
    

    Don't depend on isSelected as cells are dequeued and when you scroll you'll get unexpected results