如何动态更改UICollectionView图像的borderColor

时间:2019-07-30 13:18:12

标签: ios swift uicollectionview uicolor

我正在尝试构建一个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])
}

这是我为实现此目的而创建的代码。 有什么建议吗?谢谢

1 个答案:

答案 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