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

时间:2016-12-15 06:38:59

标签: ios uicollectionview swift3 uicollectionviewcell

 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方法中尝试了它,但它没有用。请帮忙。

2 个答案:

答案 0 :(得分:3)

您可以使用UICollectionViewCell cellForItemAt indexPath属性,在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 }

backgroundColor

现在使用此功能,无需更改didSelectItemAt indexPathbackgroundColor的单元格,它将自动生效并更改所选单元格的{{1}}。

答案 1 :(得分:0)

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)

}

}