0
votes

I have a UICollectionView. When an user clicks a cell the colour of the cell changes to red. I have coded the above part and it works perfectly.

However, when I scroll below, other cells in the collection view has got highlighted with the colour red. I am sure that it hasn't been selected but only highlighted.

How can I solve this.

My code is as follows:

cellForItemAtIndexPath Method

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"cell";

    ViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    vc.vciv.image = [arrayOfImages objectAtIndex:indexPath.row];

    return vc;

}

didSelectItemAtIndexPath Method

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    if([items  containsObject:allItem[indexPath.row]] ){
        UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
        c.backgroundColor = [UIColor clearColor]; 
    } else {
        UICollectionViewCell *c =[collectionView cellForItemAtIndexPath:indexPath];
        c.backgroundColor = [UIColor redColor]; 
 }
1
You need to keep track of the selected index and make sure you set the cell background color to either red or clear in cellForItemAtIndexPath - Paulw11

1 Answers

1
votes

As the collection view cells get reused, you need to make sure a dequeued cell is not highlighted in the cellForItemAtIndexPath: method:

UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [UIColor clearColor];

This code will clear the cell's background always when dequeuing. If you need to preserve the highlighting, you need to store the indexPaths of the cells that you want to have highlighted, and check for the current cell being in that list.

EDIT

It seems that your items variable is well suited to do that. So you would do:

UICollectionViewCell *vc = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
vc.backgroundColor = [items containsObject:allItem[indexPath.row]] ? [UIColor redColor] : [UIColor clearColor];