Swift: UICollectionViewCell didSelectItemAtIndexPath Change backgroundColor

前端 未结 4 1036
傲寒
傲寒 2021-02-09 15:39

I\'m easily able to change the background color of a cell in the CellForItemAtIndexPath method

func collectionView(collectionView: UICollectionView,         


        
4条回答
  •  抹茶落季
    2021-02-09 16:05

    Old question, but it can help someone:

    You can't simply modify the cell, since your changes will be lost when you scroll your UICollectionView, or even worst, other cells could appear with a wrong background, because they'll be reused.

    So, the best way to do that is create an array of NSIndexPath and append your selected indexPaths:

    var selectedIndexes = [NSIndexPath]() {
        didSet {
            collectionView.reloadData()
        }
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
        // ...
        if let indexSelecionado = selectedIndexes.indexOf(indexPath) {
            selectedIndexes.removeAtIndex(indexSelecionado)
        } else {
            selectedIndexes.append(indexPath)
        }
    }
    
    // ...
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // ...
        if self.selectedIndexes.indexOf(indexPath) == nil {
            cell.backgroundColor = UIColor.whiteColor() // Unselected
        } else {
            cell.backgroundColor = UIColor.redColor() // Selected
        }
        return cell
    }
    

提交回复
热议问题