持久化集合视图单元格选择

Persistent Collection View Cell Selection

请耐心等待,因为我是 swift 编程的新手。

我有一个 myCollectionViewControllerUICollectionViewController 的子class。 MyCollectionViewController 的单元格是 MyCollectionViewCell 的 class,这是自定义的 UICollectionViewCell

我想做的是根据用户选择更改 MyCollectionViewCell 的背景,并在用户滚动到 MyCollectionViewController 的其他单元格时保持此选择。我已经尝试了两种方法来做到这一点,但到目前为止都失败了。

第一种方式是在MyCollectionViewControllerdidSelectItemAt方法中编写代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell

    cell.contentView.backgroundColor = UIColor.red
}

但是,这没有用,单元格颜色没有改变。

我尝试这样做的另一种方法是更改​​ MyCollectionViewCell.

isSelected 属性
override var isSelected: Bool {
    // Change what happens when the user selects a cell

    didSet {

        if self.isSelected {
            self.contentView.backgroundColor = Colours.primary

        } else {
            self.contentView.backgroundColor = Colours.secondary

        }  
    }
}

虽然这有效,但选择没有保留。也就是说,当用户滚动到 collectionView 中的另一个单元格然后向后滚动时,选择消失了。

如有任何建议,我们将不胜感激。

不要在 didSelectItemAt 中使用 dequeue,因为它 return 除了被点击的

之外的其他单元格
var allInde = [IndexPath]()

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

    let cell = collectionView.cellForItem(at:indexPath) as!   MyCollectionViewCell

    cell.contentView.backgroundColor = UIColor.red

    if !(allIndex.contains(indexPath)) {
        allInde.append(indexPath)
    }
}

并在 cellForItem 中检查要显示的索引路径是否在数组中并为其着色

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "id", for: indexPath as IndexPath) as! MyCollectionViewCell

       if allIndex.contains(indexPath) {
          cell.contentView.backgroundColor = Colours.primary
       }
       else {
          cell.contentView.backgroundColor = Colours.secondary
       }
  }

// 在这里更新代码

SPRAIN