ios - 点击 UICollectionView 时更改单元格颜色

标签 ios swift uicollectionview

我正在开发一个带有 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/

相关文章:

ios - 如何使每个 UIView 的底部与圆相切,以便它们从中心辐射?

iphone - 基于 View 的应用程序中的选项卡栏 - XCode

swift - CAGradientLayer 旋转到横向后仅占据屏幕的一半

Swift 将数据发送到不同 Storyboard中的 View Controller

ios - PickerView 中的一个按钮在 iOS 7 中不起作用

ios - 使自定义 View 的框架适合在 drawRect 中绘制的图像

ios - 在 Xcode 8 (Swift 3) 中手动导入 Firebase Framework

swift - 如果强制关闭应用程序,NSUserDefault 数据将无法保存。 swift

objective-c - UICollectionView:自定义UICollectionViewFlowLayout header (多个 header 和 header 位置)

swift - UICollectionViewCell alpha 在使用 '.reloadItems' 时没有改变