有没有办法只允许对特定部分进行多项选择?下面的代码影响所有部分。
[self.collectionView setAllowsMultipleSelection:YES];
我应该跟踪状态并在
didSelect
中做一些事情吗? 最佳答案
您可以通过在 shouldSelectItemAtIndexPath:
实现中实现 UICollectionViewDelegate
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];
}
}
}
关于ios - UICollectionView 允许对特定部分进行多项选择,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32697992/