Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView allow multiple selection for specific section

Is there a way to allow multiple selection only for a specific section? The code below affects all sections.

[self.collectionView setAllowsMultipleSelection:YES];

Should i keep track of the states and do something in didSelect?

like image 799
bruno Avatar asked Mar 14 '23 17:03

bruno


1 Answers

You can control cell selection by implementing shouldSelectItemAtIndexPath: method in your UICollectionViewDelegate implementation.

For example, this code allows selection of any number of cells at section 1 but only one cell of any other section:

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.indexPathsForSelectedItems.count == 0 && indexPath.section == 1;
}

If you require a more complex behavior you can implement it at didSelectItemAtIndexPath. For example, this code will allow multiple selection only at section 1 and will allow only one cell selected at any other section:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1)
        return;

    NSArray<NSIndexPath*>* selectedIndexes = collectionView.indexPathsForSelectedItems;
    for (int i = 0; i < selectedIndexes.count; i++) {
        NSIndexPath* currentIndex = selectedIndexes[i];
        if (![currentIndex isEqual:indexPath] && currentIndex.section != 1) {
            [collectionView deselectItemAtIndexPath:currentIndex animated:YES];
        }
    }
}
like image 53
redent84 Avatar answered Apr 09 '23 11:04

redent84