UICollectionView Enable deselecting cells while allowsMultipleSelection is disabled

喜欢而已 提交于 2019-12-10 17:45:51

问题


When

collectionView.allowsMultipleSelection = YES;

I can deselect cells that were selected.

when

collectionView.allowsMultipleSelection = NO;

I cannot deselect cells that were selected.

Is there anyway I can only set

collectionView.allowsMultipleSelection = NO;

and

be able to deselect the selected cell? so there would either be one selected or none selected.

I understand you can implement your own selection with a tap gesture then calling setSelected when gesture is detected. But I am looking for a more native solution, something that you could configure on uicollectionView itself.

Thanks!


回答1:


I had the same problem and couldn't find a native solution. This is how I ended up doing it, a bit hacky but it does what's needed. I have self.collectionView.allowsMultipleSelection = YES set in viewDidLoad.

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    for (NSIndexPath *selectedIndexPath in [self.collectionView indexPathsForSelectedItems]) {
        [self.collectionView deselectItemAtIndexPath:selectedIndexPath animated:NO];
    }
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
}


- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

The additional selection and deselection in didDeselectItemAtIndexPath is to animate the deselection - an additional benefit this approach provides, being able to animate the transitions.



来源:https://stackoverflow.com/questions/32423778/uicollectionview-enable-deselecting-cells-while-allowsmultipleselection-is-disab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!