2015-09-06 72 views
2

UICollectionView启用取消选择细胞,而allowsMultipleSelection禁用

collectionView.allowsMultipleSelection = YES; 

我可以取消选择中选定的细胞。

collectionView.allowsMultipleSelection = NO; 

我无法取消选择中选定的细胞。

反正我只能设置

collectionView.allowsMultipleSelection = NO; 

能够取消选定单元格?所以可能会有一个被选中或者没有被选中。

我知道你可以通过点击手势来实现你自己的选择,然后在检测到手势时调用setSelected。但我正在寻找一个更原生的解决方案,你可以在uicollectionView自己配置的东西。

谢谢!

+0

也许最简单的方法是允许多重选择并清除'didSelect ...中的先前选择' – Paulw11

回答

2

我有同样的问题,找不到原生解决方案。这就是我最终做到的,有点冒险,但它确实需要。我有self.collectionView.allowsMultipleSelection = YES设置在viewDidLoad

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { 
    for (NSIndexPath *selectedIndexPath in [self.collectionView indexPathsForSelectedItems]) { 
     [self.collectionView deselectItemAtIndexPath:selectedIndexPath animated:NO]; 
    } 
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone]; 
} 


- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath { 
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone]; 
    [collectionView deselectItemAtIndexPath:indexPath animated:YES]; 
} 

附加选择和取消选择在didDeselectItemAtIndexPath是动画取消选择 - 这种方法提供了额外的益处,能够进行动画的过渡。