问题
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?
回答1:
Its because cells can be re-used right? thats why you are getting this result.
Solution is
Save the selected indexpath at somewhere.
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
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.
来源:https://stackoverflow.com/questions/14416189/uicollectionview-tap-selects-more-than-one-cell