I currently have 4 different collection views on a view, and I want to allow deselection. For this I have to set:
//Stop multiple selections on collectionview
self.bagsCollectionView.allowsMultipleSelection = YES;
self.shoesCollectionView.allowsMultipleSelection = YES;
self.dressesCollectionView.allowsMultipleSelection = YES;
self.jewelleryCollectionView.allowsMultipleSelection = YES;
However I only want to be able to select one cell from each collectionview. E.g., in bagsCollectionView the user can choose one bag but can also deselect that and pick another bag. They cannot pick two bags or two shoes. Same for the other three collection views!
How do I do this?
There's no built-in support to deselect a selected cell (by tapping it again) when allowsMultipleSelection
is disabled. But this is both intentional and intuitive. The default behavior is not meant to model a switch that you can toggle on, then toggle off.
When you consider a single-selection design where an item (or table row) is selected, when a user wants to select a different item (or table row), the intuitive behavior is to tap another item (at which point the original item is automatically deselected by the system). They don't (think about needing to) tap the original item to deselect it before selecting the other item.
You may be trying to model something that isn't generally expected, and by presenting a different interaction from other apps, it would be slightly disorienting from a UX point of view. The user may not consciously know what's wrong, but it may tinge the whole app experience.
That may represent a design problem (as well as involve some unnecessary code).
How to handle your requirement
To implement deselection but enforce single-selection, you'll need to enable multiple selection, then enforce deselection of other cells when a new selection is made.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSArray *indexPaths = collectionView.indexPathsForSelectedItems;
// Don't deselect our own index path
[indexPaths removeObject:indexPath];
for (NSIndexPath *otherIndexPath in indexPaths) {
[collectionView deselectItemAtIndexPath:otherIndexPath animated:YES];
}
// ... Do whatever else you need to do in response to the selection
}