2015-06-15 94 views
1

我想更改所选单元格的单元格背景色,但任何时候我选择一个单元格,它都会更改所选单元格和另一个随机单元格的背景颜色。什么可能是错的?UICollectionViewCell更改多个单元格的背景颜色

这里是我的代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell 
    cell.contentView.backgroundColor = UIColor.orangeColor() 
    return cell 
} 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){ 
    let cell = colorCollection.cellForItemAtIndexPath(indexPath) 
    cell?.backgroundColor = UIColor.blackColor() 
} 

回答

0

第一件事情,难道你真的想设置单元格的背景色,而不是内容视图的?我想应该是这样的:

cell.backgroundColor = UIColor.orangeColor() 

然后,你可以去设置所选的背景图的颜色是这样的:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell 
    cell.backgroundColor = UIColor.orangeColor() 

    let selectionView = UIView() 
    selectionView.backgroundColor = UIColor.blackColor() 
    cell.selectedBackgroundView = selectionView 

    return cell 
} 
相关问题