2015-09-06 40 views
2

UICollectionView啓用取消選擇細胞,而allowsMultipleSelection禁用

collectionView.allowsMultipleSelection = YES; 

我可以取消選擇中選定的細胞。

collectionView.allowsMultipleSelection = NO; 

我無法取消選擇中選定的細胞。

反正我只能設置

collectionView.allowsMultipleSelection = NO; 

能夠取消選定單元格?所以可能會有一個被選中或者沒有被選中。

我知道你可以通過點擊手勢來實現你自己的選擇,然後在檢測到手勢時調用setSelected。但我正在尋找一個更原生的解決方案,你可以在uicollectionView自己配置的東西。

謝謝!

+0

也許最簡單的方法是允許多重選擇並清除'didSelect ...中的先前選擇' – Paulw11

回答

2

我有同樣的問題,找不到原生解決方案。這就是我最終做到的,有點冒險,但它確實需要。我有self.collectionView.allowsMultipleSelection = YES設置在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]; 
} 

附加選擇和取消選擇在didDeselectItemAtIndexPath是動畫取消選擇 - 這種方法提供了額外的益處,能夠進行動畫的過渡。