如何更改 swift iOS 中自定义 Collection View 单元格的背景颜色?

How to change the background color of a custom Collection View cell in swift iOS?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell

    //let imageView = UIImageView()
    //cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)

    cell.layer.borderWidth = 0.5
    cell.layer.borderColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor

   //cell.placeLabel.tintColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00).cgColor

    cell.layer.cornerRadius = 40
    cell.layer.masksToBounds = true

    print("places\(indexPath.row)")
    //cell.placeLabel.text = places[indexPath.row] as! String
    cell.placeLabel.text = places[indexPath.row]
    cell.placeLabel.textColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)

    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell

    if (indexPath.row == 0){

        cell.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00)

    }
}

我创建了一个自定义 collectionViewCell。当我单击其中一个单元格时,它的 backgroundColor 应该改变。我怎样才能做到这一点?

我已经尝试过 didSelectItemItamAt indexpath 方法,但它不起作用。请帮忙。

将此写在您的 cellForItemAtdidSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell

if (indexPath.row == 0){

cell.backgroundColor =  UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) 
cell.contentView.backgroundColor =  UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) 
collectionView.reloadItemsAtIndexPaths(indexPath)

}

}

您可以使用 UICollectionViewCellselectedBackgroundView 属性,在 cellForItemAt indexPath 中设置 属性,现在当您 select 单元格时它会自动更改该单元格的 backgroundColor

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PlaceCollectionViewCell
     //Your other code

     //Add code to set selectedBackgroundView property
     let view = UIView(frame: cell.bounds)
     // Set background color that you want
     view.backgroundColor = UIColor(colorLiteralRed: 0.278, green: 0.694, blue: 0.537, alpha: 1.00) 
     cell.selectedBackgroundView = view
     return cell
}

现在使用它,无需更改 didSelectItemAt indexPath 中单元格的 backgroundColor 它会自动工作并更改 selected 单元格的 backgroundColor