UICollectionView Tap selects more than one cell
I have a weird issue when clicking one UICell in a UICollectionView and then scrolling down or up in the UICollectionView. I can see that more than one cell is selected. The rest of the cells that are not selected appear to be randomly selected in the UICollectionView layout. I have 3 columns of cells and many rows in a 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 highlighting code just puts a border on the found cell.
Is there a way to ensure that only the selected cell is selected?
source to share
Is it because cells can be reused correctly? that's why you are getting this result.
Decision
-
Save the selected index path somewhere.
-
Subclass your cell from UICollectionViewCell, then override the UICollectionViewCell prepareForReuse method , you need to reset from all the formatting you did (in the didSelectItemAtIndexPath method) to their default values ββand make the cell ready to use again. More on prepareForReuse here
-
Apply the same formatting again in cellForRowItemAtIndexPath to the selected cell that the index path was stored first. here it is!
But in the end, I would guess that there is no need to do any type of cell formatting here. Try to understand UICollectionViewLayoutAttributes and use it to do things like this there.
source to share