ios - 持久化 Collection View 单元格选择

标签 ios swift uicollectionview uicollectionviewcell

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

我有一个 myCollectionViewController,它是 UICollectionViewController 的子类。 MyCollectionViewController 的单元格是 MyCollectionViewCell 的一个类,这是一个自定义的 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
}

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

我尝试这样做的另一种方法是更改​​ MyCollectionViewCellisSelected 属性。

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,因为它会返回点击的单元格以外的单元格

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

关于ios - 持久化 Collection View 单元格选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239584/

相关文章:

ios - iPhone 的图像尺寸不正确-

ios - 使用带有 AutoLayout 的 UICollectionView 实现聊天布局

ios - 在 tableview 上添加一个 View

ios - JavasScriptCore 异步回调

swift - NSHTTPRESPONSE 不是@lvalue $T3 的子类型

ios - 如何设置 ViewController 的语言而不是设备的语言?

ios - 旋转时未调用 UICollectionViewDelegateFlowLayout 方法

swift - 如何将按钮添加到 CollectionView 的末尾(不在最后一个单元格中)?

ios - Unity FB SDK on iOS : Problems with FB. Feed 功能

swift - 为什么 'image' 不是 'UIImageView' 或 'UIImage' 的成员?