[英]Change cell colour when tapped UICollectionView
I'm working on an app with a UICollectionView, and I use didSelectItemAt
to change a boolean's value, but I need to make the cell colour change when I tap on it. 我正在使用带有UICollectionView的应用程序,并且我使用
didSelectItemAt
来更改布尔值,但是当我点击它时,需要更改单元格的颜色。 This is the didSelectItemAt
that I am using: 这是我正在使用的
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")
}
}
Am I doing this the right way, or is there another? 我是否以正确的方式进行操作,或者还有其他方法?
Replace 更换
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
with 与
let cell = collectionView.cellForItem(at: indexPath) as! PhotoCell
Or better after you apply the changes to the model reload that indexPath 或者将更改应用到模型后重新加载该indexPath更好
collectionView.reloadItems(at:[indexPath])
dequeueReusableCell shouldn't be used out of cellForItemAt
dequeueReusableCell不应在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])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.