3

I have a strange problem when tapping a single UICell in UICollectionView and then scrolling down or up in the UICollectionView I see that more one cell is selected. The other cells that are selected that were not tapped seem to be randomly selected throughout the UICollectionView layout. I have 3 columns of cells and many rows in the UICollectionView.

In my code I have the following:

- (void)collectionView:(UICollectionView *)myCV didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LogInfo(@"Item Selected");
    // highlight the cell user tapped on
    UICollectionViewCell  *cell = [myCV cellForItemAtIndexPath:indexPath];
    [cell.layer setBorderWidth:10.0f];
    cell.layer.borderColor = [UIColor colorWithRed: 108/255. green: 166/255. blue: 16/255. alpha:1.0].CGColor;
    cell.layer.CornerRadius = 10;

}

The highlight code just puts a border on the tapped cell.

Is there a way to make sure that only the cell that is tapped is selected?

motionpotion
  • 2,656
  • 6
  • 42
  • 60

1 Answers1

2

Its because cells can be re-used right? thats why you are getting this result.

Solution is

  1. Save the selected indexpath at somewhere.

  2. Subclass your cell from UICollectionViewCell, then override UICollectionViewCell's prepareForReuse method, there you have to reset from all the formatting you have done (in didSelectItemAtIndexPath method) to their default values and make the cell ready to use again. More about prepareForReuse is here

  3. Apply the same formatting again in cellForRowItemAtIndexPath to selected cell which indexpath you have saved first. thats it!

But finally, I would suggest that don't do any cell formatting kind of things directly here. Try to understand UICollectionViewLayoutAttributes and use it to do these kind of stuff there.

Jirune
  • 2,310
  • 3
  • 21
  • 19
  • Hi Jirune. Thank you for replying."Save the selected indexpath at somewhere." Could you explain a bit more where I should be saving it? – motionpotion Jan 25 '13 at 19:45
  • Hmm.Just declare one global NSIndexPath variable, then assign the selected indexpath to that variable, now based on that stored index you just apply your formattings in cellForItemAtIndexPath thats it.. – Jirune Jan 26 '13 at 19:08