【问题标题】:UICollectionView: Random Cell highlightedUICollectionView:随机单元格突出显示
【发布时间】:2018-06-21 12:54:35
【问题描述】:

我有一个包含各种单元格的集合视图。可以一次选择一个,选择状态存储在我的业务逻辑中。如果选择了一个单元格,则会重新加载整个部分以更新 UI 以突出显示当前选定的单元格。

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    ...
    cell.setItemSelected(selected: selected)
    return cell
    }

我的问题是随机单元格会在短时间内突出显示。 我还实现了prepareForReuse(),但没有任何效果。

这是什么原因造成的?

谢谢!

这里要求的附加代码:

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

        let pendencyDeficiencyType = deficiencyTypes[indexPath.row]

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PendencyDetailCell.reuseIdentifier, for: indexPath) as? PendencyDetailCell{
            cell.titleLabel.attributedText = StringUtils.hyphenedText(pendencyDeficiencyType.rawValue)
            cell.indexPath = indexPath
            cell.delegate = self

            let selected = pendencyDeficiencyType == pendencyItem?.pendencyDeficiencyType
            cell.setItemSelected(selected: selected)

            return cell
        }
        return collectionView.dequeueReusableCell(withReuseIdentifier: PendencyDetailCell.reuseIdentifier, for: indexPath)
    }

override func prepareForReuse() {
    super.prepareForReuse()
    backgroundColor = Styling.cellDefaultColor
    titleLabel.textColor = .black
}

func setItemSelected(selected: Bool){
        layer.borderColor = selected ? Styling.heagPrimary.cgColor :  UIColor.darkGray.cgColor
        backgroundColor = selected ? Styling.cellSelectedColor : Styling.cellDefaultColor
        titleLabel.textColor = selected ? .white : .black
    }

【问题讨论】:

  • 你需要分享更多(相关)代码
  • ...替换的代码是什么?这可能就是问题所在。
  • 编辑您的问题以显示您的整个collectionView(_:cellForItemAt:) 方法以及您的prepareForReuse() 方法。魔鬼在细节中。
  • 我已经编辑了我的帖子
  • 当您知道从collectionview中出列的可重用单元格时,您需要处理未选择项目时的else情况

标签: ios swift uicollectionview


【解决方案1】:

作为一种选择,您可以实现两个单独的单元格.. 一个用于每个状态并根据标志使用它。

尝试根据标志使用不同的 ReuseIdentifiers。

【讨论】: