Swift4,选定单元格时的背景色

时间:2018-09-11 12:52:44

标签: ios swift uikit

我正在尝试突出显示用户选择的单元格背景。 当用户选择一个单元格时,我已经成功地更改了它的边框。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    addToList.append(objectsArray[indexPath.row])
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.contentView.layer.borderWidth = 2.0
    cell?.contentView.layer.borderColor = UIColor.gray.cgColor
}

虽然我无法更改背景。

可以做到吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

对于单元格边框,请像这样使用cell contentView

cell?.contentView.layer.borderWidth = 2.0
cell?.contentView.layer.borderColor = UIColor.gray.cgColor

对于单元格backgroundColor颜色,您需要使用:

cell?.backgroundColor = .gray

答案 1 :(得分:1)

尝试一下。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell.contentView.backgroundColor = UIColor.red
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell.contentView.backgroundColor = UIColor.white
}
相关问题