我正在开发一个带有 UICollectionView 的应用程序,我使用 didSelectItemAt
更改 bool 值,但我需要在点击它时更改单元格颜色。这是我正在使用的 didSelectItemAt
:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let caseName = OLLData.list[indexPath.item].image
print(caseName, OLLData.list[indexPath.item].selected)
OLLData.list[indexPath.item].selected = !OLLData.list[indexPath.item].selected
if OLLData.list[indexPath.item].selected == true {
cell.imageView.backgroundColor = UIColor.yellow
print("Changed Colour to Yellow")
}
else {
cell.imageView.backgroundColor = UIColor.clear
print("Changed Colour to Clear")
}
}
我这样做的方式是否正确,还是有其他方式?
最佳答案
替换
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
与
let cell = collectionView.cellForItem(at: indexPath) as! PhotoCell
或者在将更改应用到模型后更好地重新加载 indexPath
collectionView.reloadItems(at:[indexPath])
dequeueReusableCell shouldn't be used out of cellForItemAt
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
cell.imageView.backgroundColor = OLLData.list[indexPath.item].selected ? UIColor.yellow : UIColor.clear
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let caseName = OLLData.list[indexPath.item].image
print(caseName, OLLData.list[indexPath.item].selected)
OLLData.list[indexPath.item].selected = !OLLData.list[indexPath.item].selected
collectionView.reloadItems(at:[indexPath])
}
关于ios - 点击 UICollectionView 时更改单元格颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713387/