关于 UICollectionViewCell 的一些陷阱

如果直接使用 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 非选中 状态下的样式。

posted @ 2016-04-13 11:32  AntonyGu  阅读(2808)  评论(0编辑  收藏  举报