如何在swift iOS中更改自定义集合视图单元格的背景色?

如何在swift iOS中更改自定义集合视图单元格的背景色?,ios,uicollectionview,swift3,uicollectionviewcell,Ios,Uicollectionview,Swift3,Uicollectionviewcell,我创建了一个自定义的collectionViewCell。当我点击其中一个单元格时,它的backgroundColor应该会改变。我怎样才能做到这一点 我在didselectitemitamatindexpath方法中尝试过它,但它不起作用。请提供帮助。在您的cellForItemAt或didSelectItemAt func collectionView(collectionView:UICollectionView,didSelectItemAt indexPath:indexPath){

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


我在
didselectitemitamatindexpath
方法中尝试过它,但它不起作用。请提供帮助。

在您的
cellForItemAt
didSelectItemAt

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

}

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

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)

}

现在使用此方法,无需更改
didSelectItemAt indexPath
中单元格的
backgroundColor
,它将自动工作,并更改所选单元格的
backgroundColor

didselectpath方法是否调用?@jigneshvadadorya不,它没有调用确保您的CollectionView.allowselection=true然后它会打电话来didItemSelectpath@RakeshMohan你试过我的解决方案吗?@NiravD,它起作用了。谢谢,我必须在if(indexpath.row)条件下编写上述代码,对吗?我需要在单击集合视图单元格时实现这一点。我认为这不是正确的方法。为什么我们在这里为UIView分配浪费内存??因为我们可以在不分配UIView的情况下执行此操作。@DheerajD这是处理OP所需内容的最佳方法,您在发布评论之前是否尝试过,另外,在你的代码中,你只是在更改单元格的颜色。当collectionView滚动时,op正在重复使用单元格的情况如何?它将更改其他单元格的背景颜色,而不是选定的单元格。当取消选择单元格时,你还没有删除背景颜色。Nirav是的,我没有运行代码,因为我已修复了同一个单元格的背景颜色前一段时间发行。我再次不同意你的观点,对于改变背景颜色的袋子,我为什么要允许UIView?正如你所说的滚动后,它会改变颜色,所以它是正确的,它会。我知道答案是根据它的当前版本,而不是整个功能。@DheerajD如果你不知道事情是如何运作的,那就离开它吧。
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)

}
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
}