选择时 UICollectionviewCell backgroundColor 不更改

UICollectionviewCell backgroundColor not Change when selected

我正在尝试更改单元格选中时的背景颜色。但是单元格背景颜色没有改变。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CategoryCollectionViewCell
    let category = self.categories[indexPath.row]
    switch cell.isSelected {
    case true:
        cell.backgroundColor = .black
    default:
        cell.backgroundColor = .white
    }
    cell.setNeedsDisplay()    
}

您应该使用以下两种集合视图委托方法:

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

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

  cell.backgroundColor = .black
}

而且,

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

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

  cell.backgroundColor = .white
}

您无需在选择时手动更改背景颜色。 UICollectionViewCell 有一个 属性 叫做 selectedBackgroundView 正是为了这个目的。

在您的 collectionView(_:cellForItemAt:) 委托方法中使用它,如下所示:

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

    cell.selectedBackgroundView = UIView(frame: cell.bounds)
    cell.selectedBackgroundView!.backgroundColor = .black

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

    if let cell = collectionView.cellForItem(at: indexPath) {
        cell.backgroundColor = cell.isSelected ? .black : .white
    }
}

在 didSelect 委托方法中尝试以下操作:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let selectedCell = collectionView.cellForItemAtIndexPath(indexPath)

    selectedCell?.backgroundColor = UIColor.blueColor()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
    let cell = collectionView.cellForItem(at: indexPath) as! CustomCell
    cell.cellView.backgroundColor = .red
    
}

我认为通过观察其 属性 isSelected,处理单元格的背景颜色应该成为单元格的一部分。它处理一个单元格的 selection 和 un-selection,否则在 selection of任何其他单元格,例如:

class MyCustomCollectionViewCell: UICollectionViewCell {
    override var isSelected: Bool {
        didSet {
            contentView.backgroundColor = isSelected ? .red : .white
        }
    }
}