UICollectionView Tap 选择多个单元格 [英] UICollectionView Tap Selects More Than One Cell

查看:17
本文介绍了UICollectionView Tap 选择多个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在点击 UICollectionView 中的单个 UICell 然后在 UICollectionView 中向下或向上滚动时遇到一个奇怪的问题,我看到选择了更多一个单元格.被选中但未被点击的其他单元格似乎是在整个 UICollectionView 布局中随机选择的.我在 UICollectionView 中有 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?

推荐答案

是因为单元格可以重复使用吗?这就是你得到这个结果的原因.

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

解决方案是

  1. 将选定的索引路径保存在某处.

  1. Save the selected indexpath at somewhere.

从 UICollectionViewCell 子类化您的单元格,然后覆盖 UICollectionViewCell 的 prepareForReuse 方法,您必须将已完成的所有格式设置(在 didSelectItemAtIndexPath 方法中)重置为默认值并使单元格准备再次使用.有关 prepareForReuse 的更多信息是 这里

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

在 cellForRowItemAtIndexPath 中再次应用相同的格式到您首先保存的索引路径的选定单元格.就是这样!

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

但最后,我建议不要直接在这里进行任何单元格格式设置.尝试了解 UICollectionViewLayoutAttributes 并使用它在那里做这些事情.

这篇关于UICollectionView Tap 选择多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆