CollectionView, change Cell color

3.2k views Asked by At

i have collectionView with 52 images in it,

on didSelectItemAtIndexPath method i have this code:

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

background color is changing, BUT, when i scroll down my collectionView, another cell there have green background color, I assume collectionView doing some redrawing and some strange things happen with indexPath or something,

Could really use advice on how to change color of just one cell, even when you scroll collection view up and down,

Thanks!

D

3

There are 3 answers

7
MKoosej On BEST ANSWER

The cell is getting reused. That's the reason. In your cell class you should add the default background in the prepareForReuse method. Or you can set background in your cellforItemAtIndexPath. The first approach is better.

7
Fadi Obaji On

Edited

In your CustomCell.m file:

-(void)setHighlighted:(BOOL)highlighted
{
if (highlighted)
{
    self.layer.opacity = 0.6;
    //or whatever you want here
}
else{
    self.layer.opacity = 1.0;
    //revert back the changes 
}
}

And you're good to go.

Hope that helps :)

0
Deniss On

thanks to MKoosej and other guys,

I managed to get it work,

had to add method to my customCell.swift:

override func prepareForReuse() {
        self.backgroundColor = UIColor.clearColor()
    }

then in cellForItemAtIndexPath, i check stored indexPath.row, if its was selected then i changed color.

Now it works when you scroll.

Thanks again, learned something new!

Deniss