UICollectionView Tap Selects More Than One Cell

蹲街弑〆低调 提交于 2020-01-14 15:01:29

问题


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

  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.



来源:https://stackoverflow.com/questions/14416189/uicollectionview-tap-selects-more-than-one-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!