Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS UICollectionView cell selection per section

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!

like image 377
Rohan Agarwal Avatar asked Aug 29 '26 04:08

Rohan Agarwal


2 Answers

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!

like image 57
Pablo Avatar answered Aug 31 '26 20:08

Pablo


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

like image 34
Asaf Baibekov Avatar answered Aug 31 '26 21:08

Asaf Baibekov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!