I was wondering how to set up my UICollectionView so that up to 1 cell can be selected per section. I see that there is the allowsMultipleSelection property for UICollectionView but I'm wondering how to prevent multiple cells from being selected in the same section.
Do I need to implement logic in the – collectionView:shouldSelectItemAtIndexPath: and collectionView:shouldDeselectItemAtIndexPath: methods or is there a simpler way?
Thanks!
In your didSelectRowAtIndexPath you could do something like this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
NSArray * selectedRows = self.tableView.indexPathsForSelectedRows;
for (NSIndexPath * selectedRow in selectedRows) {
if ((selectedRow.section == indexPath.section) && (selectedRow.row != indexPath.row)) {
[self.tableView deselectRowAtIndexPath:selectedRow animated:NO];
}
}
}
allowsMultipleSelection should be set to YES.
Hope it helps!
In Swift 5.0:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.allowsMultipleSelection = true
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
(collectionView.indexPathsForSelectedItems ?? [])
.filter { $0.section == indexPath.section && $0.item != indexPath.item && $0.row != indexPath.row }
.forEach { self.collectionView.deselectItem(at: $0, animated: false) }
}
if you want it to toggle between items in section use this:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.allowsMultipleSelection = true
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
(collectionView.indexPathsForSelectedItems ?? [])
.filter { $0.section == indexPath.section && $0.item }
.forEach { self.collectionView.deselectItem(at: $0, animated: false) }
}
I think that makes better user experience but it's your call
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With