我正在尝试构建一个UICollectionView
,该像素在每个单元格内都有一个黑色的borderColor图像。当用户触摸该项目时,我希望它将borderColor更改为红色并返回。
我已经实现了,但是在初次接触时不起作用:
Video of the problem,很抱歉,但我不知道如何将视频放入StackOverflow。
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = myCollectionView?.cellForItem(at: indexPath) as! CategoriesChoosingCell
if cell.layer.borderColor == UIColor.red.cgColor {
cell.imgView.layer.borderColor = UIColor.black.cgColor
} else {
cell.imgView.layer.borderColor = UIColor.red.cgColor
}
myCollectionView!.reloadItems(at: [indexPath])
}
这是我为实现此目的而创建的代码。 有什么建议吗?谢谢
答案 0 :(得分:0)
在模型内部添加
class Item {
var isBlack = true // or false
}
然后在cellForRowAt
内
let cell = ///
cell.imgView.layer.borderColor = items[indexPath.row].isBlack ? UIColor.black.cgColor : UIColor.red.cgColor
然后
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let item = items[indexPath.row]
item.isBlack = !(item.isBlack)
myCollectionView!.reloadItems(at: [indexPath])
}
这对于多重选择很有用,对于在vc中单声明一个变量并检查是否
selectedRow == indexPath.row
代替
items[indexPath.row].isBlack