【发布时间】:2015-12-18 07:36:07
【问题描述】:
有没有办法只允许对特定部分进行多项选择?下面的代码会影响所有部分。
[self.collectionView setAllowsMultipleSelection:YES];
我应该跟踪状态并在didSelect 中做点什么吗?
【问题讨论】:
标签: ios uicollectionview uicollectionviewcell didselectrowatindexpath
有没有办法只允许对特定部分进行多项选择?下面的代码会影响所有部分。
[self.collectionView setAllowsMultipleSelection:YES];
我应该跟踪状态并在didSelect 中做点什么吗?
【问题讨论】:
标签: ios uicollectionview uicollectionviewcell didselectrowatindexpath
您可以通过在您的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];
}
}
}
【讨论】: