【问题标题】:UICollectionView allow multiple selection for specific sectionUICollectionView 允许对特定部分进行多项选择
【发布时间】:2015-12-18 07:36:07
【问题描述】:

有没有办法只允许对特定部分进行多项选择?下面的代码会影响所有部分。

[self.collectionView setAllowsMultipleSelection:YES];

我应该跟踪状态并在didSelect 中做点什么吗?

【问题讨论】:

    标签: ios uicollectionview uicollectionviewcell didselectrowatindexpath


    【解决方案1】:

    您可以通过在您的UICollectionViewDelegate 实现中实现shouldSelectItemAtIndexPath: method 来控制单元格选择。

    例如,此代码允许选择第 1 部分的任意数量的单元格,但只能选择任何其他部分的一个单元格:

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

    如果您需要更复杂的行为,您可以在didSelectItemAtIndexPath 实现它。例如,此代码将只允许在第 1 部分进行多项选择,并且只允许在任何其他部分选择一个单元格:

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

    【讨论】:

    • ShouldSelect 将始终返回 YES;那里无事可做。
    • 不确定你的意思,检查我的编辑,看看它是否符合你的需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多