多个 UICollectionViewCell 颜色一起更改问题

Multiple UICollectionViewCell color gets changed together issue

我创建了一个包含 12 个单元格的 UICollectionView。我想随时更改它们的颜色(更改为相同的颜色)。

这是我的代码:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath)as! InterestCollectionViewCell
    print("2 \(cell.interest)  \(indexPath.row)")

    if  cell.selected == true {
        cell.backgroundColor = UIColor.redColor()
    }
    else {
        cell.backgroundColor = UIColor.clearColor()
    }
}

问题

  1. 再次点击时颜色不会变回
  2. 当我点击 [0] 单元格时,[5] 和 [10] 单元格也会改变颜色。同样在我点击 [1] 单元格后,[6] 和 [11] 单元格也被调用...etc.m

不是在 didSelectItemAtIndexPath 中设置颜色,而是在 cellForItemAtIndexPath 中设置颜色,为此您需要声明 Int 的实例并将 collectionView 的行存储在该实例中像这样。

var selectedRow: Int = -1

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
    // Set others detail of cell
    if self.selectedRow == indexPath.item {
        cell.backgroundColor = UIColor.redColor()
    }
    else {
        cell.backgroundColor = UIColor.clearColor()
    }
    return cell
}

现在在 didSelectItemAtIndexPath 中设置 selectedRow 重新加载 collectionView

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if self.selectedRow == indexPath.item {
        self.selectedRow = -1
    }
    else {
        self.selectedRow = indexPath.item
    }
    self.collectionView.reloadData()
}

编辑: 对于多个单元格选择,创建一个 indexPath 数组并像这样存储 indexPath 的对象。

var selectedIndexPaths = [NSIndexPath]()

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
    // Set others detail of cell
    if self.selectedIndexPaths.contains(indexPath) {
        cell.backgroundColor = UIColor.redColor()
    }
    else {
        cell.backgroundColor = UIColor.clearColor()
    }
    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if self.selectedIndexPaths.contains(indexPath) {
        let index = self.selectedIndexPaths.indexOf(indexPath)
        self.selectedIndexPaths.removeAtIndex(index)
    }
    else {
        self.selectedIndexPaths.append(indexPath)
    }
    self.collectionView.reloadData()
}