问题:
让collectionView进入编辑模式,第一下点击cell将其标记选中并添加一个数组中,并刷新collectionView,第二次点击cell时取消标记并从数组中移除,但是此时发现didSelectItemAtIndexPath并不会被调用
原因:
当调用reloadItemsAtIndexPaths或者reloadData,会执行cellForItemAtIndexPath:, 而此时cell的selected属性又重新被初始化为NO了,所以此时cell的是处于非选中状态的,也就不会调用didDeselectItemAtIndexPath:这个方法来取消选中了。
解决方法:
在collectionView:didSelectItemAtIndexPath:方法中手动触发其为选中,在collectionView:didDeselectItemAtIndexPath:方法中再将其触发为非选中状态,此处需要注意的是reloadData方法并不是立即返回的,这时需要使用一个dispatch_async或其他方法来执行后面的操作,代码如下:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if (self.isEdit == YES) {
OSFileAttributeItem *item = self.files[indexPath.row];
item.status = OSFileAttributeItemStatusChecked;
if (![self.selectorFiles containsObject:item]) {
[self.selectorFiles addObject:item];
}
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
// 手动触发cell为选中状态
dispatch_async(dispatch_get_main_queue(), ^{
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
});
} else {
self.indexPath = indexPath;
UIViewController *vc = [self previewControllerByIndexPath:indexPath];
[self jumpToDetailControllerToViewController:vc atIndexPath:indexPath];
}
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
if (self.isEdit) {
OSFileAttributeItem *item = self.files[indexPath.row];
item.status = OSFileAttributeItemStatusEdit;
[self.selectorFiles removeObject:item];
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
// 手动触发cell为非选中状态
dispatch_async(dispatch_get_main_queue(), ^{
[collectionView deselectItemAtIndexPath:indexPath animated:YES];
});
}
}
网友评论