当启用allowMultipleSelection时,如何在UICollectionView中以编程方式取消选择单元格?

Ste*_*eve 34 iphone objective-c uicollectionview

我在集合视图中启用了allowMultipleSelection.在轻敲时,单元格会更改为选定状态.都好.但是,当我想将整个视图重置为选定状态时:NO使用下面的代码,单元格似乎完全取消选择,直到我进行新选择,此时所有先前选择的单元格显示其先前选择的状态.

即使出现,当我以编程方式取消选择单元格时,集合视图不会更新它的当前选择列表

- (void)clearCellSelections {
   for (LetterCell  *cell in self.collectionView.visibleCells) {
        [cell prepareForReuse];
    }
}
Run Code Online (Sandbox Code Playgroud)

在定制单元格中:

- (void)prepareForReuse
{
    [super prepareForReuse];
    [self setSelected:NO];
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?还有另一种取消选择所有细胞的方法吗?

谢谢TBlue看看

qor*_*end 86

你可以迭代- [UICollectionView indexPathsForSelectedItems]:

for (NSIndexPath *indexPath in [self.collectionView indexPathsForSelectedItems]) {
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
Run Code Online (Sandbox Code Playgroud)

  • 小修正.有一个`animated`参数.因此它应该是:`[self.collectionView deselectItemAtIndexPath:indexPath animated:NO];` (3认同)

tah*_*erh 19

取消选择a中所有选定单元格的最简单方法UICollectionView是简单地将其nil作为第一个参数传递给collectionView.selectItem(at:, animated:, scrollPosition:).例如,

collectionView.selectItem(at: nil, animated: true, scrollPosition: [])
Run Code Online (Sandbox Code Playgroud)

将清除当前的选择状态,即使是allowsMultipleSelection == true.


fgu*_*aar 11

你可以说UITableViewCell.selected只设置单元格的"可见状态/外观"及其内容.您可以通过迭代tableView的所有indexPath并取消每个单元格来取消选择单元格deselectRowAtIndexPath:animated:.

例如:

for (int i=0; i < self.myData.count; i++) {
    [self.tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

编辑:我完全同意@BenLings和@ JeremyWiebe的评论,@ qorkfiend的解决方案比这个更受欢迎.

  • @ qorkfiend的答案比这个更好 (3认同)