Ranu Dhurandhar
Ranu Dhurandhar

Reputation: 101

Deselect and change background of other cells in collection view when one cell is selected

I am having a collectionView where I want to select one cell at a time. And also change the background of selected cell. I am having an issue that when I select one cell in didSelectItem() method my previous selected cells background not getting change.

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {

    if let cell2 = self.segmentScrollView.cellForItem(at: selectedcellNo!) as? segmentCollectionViewCell {

        //self.segmentScrollView.reloadItems(at: [selectedcellNo!])
        cell2.segmentName.backgroundColor = .white
        cell2.segmentName.textColor = UIColor.init(red: 141/255, green: 0/255, blue: 22/255, alpha: 1.0)            
        self.segmentScrollView.deselectItem(at: selectedcellNo!, animated: true)
    }

    let cell = self.segmentScrollView.cellForItem(at: indexPath) as? segmentCollectionViewCell
    cell?.segmentName.backgroundColor =  UIColor.init(red: 141/255, green: 0/255, blue: 22/255, alpha: 1.0)
    cell?.segmentName.textColor = .white
    let dateValue = self.segmentJSON[indexPath.row]["date"].stringValue
    self.getShows(date: dateValue)
    print("selectedcellNo-now: ",selectedcellNo!)
    self.selectedcellNo! = indexPath
}

Upvotes: 1

Views: 624

Answers (1)

PGDev
PGDev

Reputation: 24341

In your custom UICollectionViewCell, override isSelected property and change the backgroundColor based on selected state in didSet observer, i.e.

class CollectionViewCell: UICollectionViewCell {
    override var isSelected: Bool {
        didSet {
            self.backgroundColor = isSelected ? .red : .white
        }
    }

    //rest of the code...
}

No need to implement didSelectItemAt in this case.

Upvotes: 2

Related Questions