2015-06-15 135 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 
} 
相關問題