Search code examples
iosuicollectionviewuicollectionviewcelldidselectrowatindexpath

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?


Solution

  • 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];
            }
        }
    }