我在CollectionView中有多个项目,但只有少数项目可供选择。我正在用委托方法处理这个:
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
如果选择了可选项,则会出现问题,并且在下一步中,如果shouldSelectItemAtIndexPath返回NO,则拒绝选择不可选项,否则将取消选择所选项。
我也尝试过使用
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
但这也是同样的问题。
这是UICollectionView的正确所需行为吗?如果是的话,如果选择了一个不可选的项目,我如何避免取消选择我最后选择的项目?
答案 0 :(得分:13)
我必须纠正我的假设:最后的选择不会被取消选择!
为了在选择时改变单元格的外观,我已经覆盖了UICollectionViewCell的setSelected访问器。 选择不可选择的项目时,会多次调用最后一个选定单元格的访问者setSelected。首先是状态NO,然后是状态YES,最后是NO。最后一个状态NO导致我的单元格将其外观设置为非选定单元格的外观。
我不知道这种奇怪行为的原因也无法解决。
我的解决方法是直接在ViewController中更改所选单元格的外观。
将选定的外观设置为:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
删除所选的外观:
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
检查当前单元格是否已选中并按预期更改外观。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
答案 1 :(得分:1)
您应该在委托方法DidSelect和DidDeselect方法中更改单元格外观。如果在shouldSelect方法中返回NO,则不会调用DidSelect和DidDeselect,因此外观将保持不变,与collectionView的选定状态一致。
答案 2 :(得分:1)
与UICollectionView
相比,我不知道为什么UITableViewController
如此混乱......
我发现了一些事情。
多次调用- setSelected:
的原因是因为调用了序列方法。该序列与UITextFieldDelegate
方法的序列非常相似。
方法- collectionView:shouldSelectItemAtIndexPath:
在collectionView
实际选择单元格之前调用,因为它实际上要求"是否应该选择"?
- collectionView:didSelectItemAtIndexPath:
选择单元格后调用{p> collectionView
。因此,名称"确实选择了。"
同样取消选择。
TL; DR - 让collectionView
通过调用- collectionView:shouldSelectItemAtIndexPath:
取消选择委托方法- selectItemAtIndexPath:animated:scrollPosition:
中的单元格,一切都会好的。
答案 3 :(得分:1)
我刚遇到同样的问题。我尝试了各种解决方案,第一个在我的情况下工作的是重新加载然后重新选择所选的单元格。无论我是重新加载整个集合视图还是只是因为未选中的外观而卡住的单元格,这对我有用。
对我不起作用的方法:
selected
属性设置为true,或者甚至将其切换为false,然后再次为true。-selectItemAtIndexPath:animated:scrollPosition:
选择项目,甚至通过-deselectItemAtIndexPath:
取消选择,然后再次选择。-reloadItemsAtIndexPaths:
-reloadData
重新加载所有内容。答案 4 :(得分:1)
我通过设置self.collectionView.allowsMultipleSelection = true
来解决这个问题。
当我将 true 返回-collectionView:shouldSelectItemAtIndexPath:
时,取消选择每个索引
答案 5 :(得分:1)
晚6年,但可能对其他人有所帮助。在这种情况下,某些单元格最初是不可选择的,则只需将isUserInteractionEnabled = false
添加到自定义UICollectionViewCell
的{{1}}函数中即可。也可以在xib文件中完成此操作,但这不太明确,可能对以后的维护者不明显。
答案 6 :(得分:0)
你试过了吗?
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
我发现这个工作符合要求。