tôi có một cái UICollectionView
(带有 .allowsMultipleSelection = true
),并且我想要它,以便每当我点击单元格时,它都会改变颜色,并且当我点击再一次,它又恢复到原来的颜色。我知道 UICollectionViewCell
有一个 isSelected
属性,因此我尝试操纵它来更改颜色。
override var isSelected: Bool {
didSet {
if isSelected == false {
contentView.backgroundColor = .lightGray
roleLabel.textColor = .gray
} khác {
contentView.backgroundColor = .gray
roleLabel.textColor = .black
print("selected")
}
}
}
包含相关 Collection View 的 View Controller 类已定义 didSelectItemAt
。但是,每当我点击单元格时,每次都会打印“selected” - 这意味着无论我点击单元格多少次,它仍然将 isSelected
设置为 ĐÚNG VẬY
每次 - 并且颜色不会改变。为什么会发生这种情况?
您必须将所选单元格存储在数组中。例如,只需将所选单元格的索引路径存储在数组中,然后检查索引路径是否已存在于数组中,这意味着它已被选中。
var slectedCell = [IndexPath]()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if slectedCell.contains(indexPath) {
cell.backgroundColor = UIColor.gray
slectedCell = slectedCell.filter { $0 != indexPath }
}
khác {
slectedCell.append(indexPath)
cell.backgroundColor = UIColor.lightGray
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if slectedCell.contains(indexPath) {
cell.backgroundColor = UIColor.gray
}
khác {
cell.backgroundColor = UIColor.lightGray
}
}
Tôi là một lập trình viên xuất sắc, rất giỏi!