UICollectionviewCell backgroundColor选中时不更改

时间:2016-11-05 21:35:57

标签: ios swift uicollectionview uicollectionviewcell

我试图在选择时更改单元格的backgorund颜色。但细胞背景颜色没有变化。

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()


    }

6 个答案:

答案 0 :(得分:2)

选择后无需手动更改背景颜色。为此,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
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

您应该使用两个集合视图委托方法,如下所示:

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
}

答案 3 :(得分:0)

在didSelect委托方法中尝试以下内容:

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

    selectedCell?.backgroundColor = UIColor.blueColor()
}

答案 4 :(得分:0)

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

答案 5 :(得分:0)

我认为通过观察单元格的属性 isSelected 来处理单元格的背景颜色应该是单元格的一部分。它处理单元格的选择和取消选择,否则在选择任何其他单元格时取消选择选定的单元格会很棘手,例如:

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