YichenBman YichenBman - 7 months ago 251
Swift Question

Swift: UICollectionViewCell didSelectItemAtIndexPath Change backgroundColor

I'm easily able to change the background color of a cell in the CellForItemAtIndexPath method

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
cell.backgroundColor = UIColor.blackColor()
}


However, when I attempt to change the color in the DidSelectItemAtIndexPath it does not work.

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell: ButtonCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCollectionCell {
cell.backgroundColor = UIColor.blackColor()


}

Also I read somewhere that using didSelectItemAtIndexPath won't work because once the collection view begins scrolling the color will change back

What is the fix in Swift?

Thank you so much for your help

Answer

You can use this method for that:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

    var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
    cell.backgroundColor = UIColor.magentaColor()
}