gpt4 book ai didi

ios - 如何允许选择和取消选择多个 UICollectionViewCell?

转载 作者:行者123 更新时间:2023-11-30 11:00:11 24 4
gpt4 key购买 nike

我有一个 UICollectionView (带有 .allowsMultipleSelection = true),并且我想要它,以便每当我点击单元格时,它都会改变颜色,并且当我点击再一次,它又恢复到原来的颜色。我知道 UICollectionViewCell 有一个 isSelected 属性,因此我尝试操纵它来更改颜色。

override var isSelected: Bool {
didSet {
if isSelected == false {
contentView.backgroundColor = .lightGray
roleLabel.textColor = .gray
} else {
contentView.backgroundColor = .gray
roleLabel.textColor = .black
print("selected")
}
}
}

包含相关 Collection View 的 View Controller 类已定义 didSelectItemAt。但是,每当我点击单元格时,每次都会打印“selected” - 这意味着无论我点击单元格多少次,它仍然将 isSelected 设置为 true 每次 - 并且颜色不会改变。为什么会发生这种情况?

最佳答案

您必须将所选单元格存储在数组中。例如,只需将所选单元格的索引路径存储在数组中,然后检查索引路径是否已存在于数组中,这意味着它已被选中。

var slectedCell = [IndexPath]()

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


if slectedCell.contains(indexPath) {
cell.backgroundColor = UIColor.gray
slectedCell = slectedCell.filter { $0 != indexPath }
}
else {
slectedCell.append(indexPath)
cell.backgroundColor = UIColor.lightGray
}

}


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

if slectedCell.contains(indexPath) {
cell.backgroundColor = UIColor.gray
}
else {
cell.backgroundColor = UIColor.lightGray
}


}

关于ios - 如何允许选择和取消选择多个 UICollectionViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53471420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com