如果直接使用 UICollectionViewCell 的自帶屬性 selected
來自定義一些樣式,如:
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
[self setNeedsDisplay];
}
,那么當你reloadData 且在
cellForItemAtIndexPath 方法中給其 selected 屬性設置YES 后,無論如何你是不能觸發下面兩個取消選中的代理方法:
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath; // called when the user taps on an already-selected item in multi-select mode
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
也就無法達到取消選中的功能。
有兩種解決方法:
1.
在 cellForItemAtIndexPath 方法中給其 selected 屬性設置YES 后,再使用 selectItemAtIndexPath: animated: scrollPoisition: 方法將其設置為選中 Item:
這樣你再點擊這個 Item 的時候就可以觸發
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath; // called when the user taps on an already-selected item in multi-select mode
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;
兩個發法。
2. 使用自定義的選中狀態屬性來代替 UICollectionViewCell 自帶的 selected 屬性:
再在此屬性的 setter 方法中自定義樣式:
那么即使你在cellForRow 中給 selectedState 賦值也不影響取消選中的代理方法的使用。然后還將出現的另一個陷阱就是:
當你(轉屏后)reloadData 以后,選中的 selected Item 將重新返回到 ”非選中Item“狀態,當你點擊的時候並不會觸發
shouldDeselectItemAtIndexPath 方法,而是觸發 shouldSelectItemAtIndexPath 方法,因此你還需在 shouldSelectItemAtIndexPath 方法中再做一次處理:
就是使用 deselectItemAtIndexPath: animated: 將其直接設置為你想取消選中的狀態,並同時處理cell 非選中 狀態下的樣式。