问题
When
collectionView.allowsMultipleSelection = YES;
I can deselect cells that were selected.
when
collectionView.allowsMultipleSelection = NO;
I cannot deselect cells that were selected.
Is there anyway I can only set
collectionView.allowsMultipleSelection = NO;
and
be able to deselect the selected cell? so there would either be one selected or none selected.
I understand you can implement your own selection with a tap gesture then calling setSelected when gesture is detected. But I am looking for a more native solution, something that you could configure on uicollectionView itself.
Thanks!
回答1:
I had the same problem and couldn't find a native solution. This is how I ended up doing it, a bit hacky but it does what's needed. I have self.collectionView.allowsMultipleSelection = YES set in 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];
}
The additional selection and deselection in didDeselectItemAtIndexPath is to animate the deselection - an additional benefit this approach provides, being able to animate the transitions.
来源:https://stackoverflow.com/questions/32423778/uicollectionview-enable-deselecting-cells-while-allowsmultipleselection-is-disab