Rohan Agarwal Rohan Agarwal - 3 months ago 31
iOS Question

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!

Answer

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!