UICollectionView reloadData不走cellForRowAtIndexPath的问题

来源:互联网 发布:如何查看淘宝卖家时间 编辑:程序博客网 时间:2024/05/14 21:51

用collectionview做一个图片展示的时候,当删除照片之后reloaddata的时候发现走了numOfRows但是却没有走cellForRowAtIndexPath导致删除之后刷新不了collectionView.


    NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:deleteBtn.tag inSection:0];    [_photos removeObjectAtIndex:deleteIndexPath.row];    [_mainView deleteItemsAtIndexPaths:@[deleteIndexPath]];    [_mainView reloadData];
因为是用tag来记录要删除那个imageview,所以当删除完一张图片之后必须刷新下collectionview才能保证删除图片是正确的。但是上面的代码刷新不了collectionview。


搜了一些资料之后发现这样写就Ok了。


[_mainView performBatchUpdates:^ {               NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:deleteBtn.tag inSection:0];        [_photos removeObjectAtIndex:deleteIndexPath.row];        [_mainView deleteItemsAtIndexPaths:@[deleteIndexPath]];            } completion:^(BOOL finished) {                //[_mainView reloadSections:[NSIndexSet indexSetWithIndex:0]];                [_mainView reloadData];        [self resetPhotosView];            }];


暂时找不到原因。。。。。第一种写法的时候用

[_mainView reloadSections:[NSIndexSet indexSetWithIndex:0]];
这个刷新是可以的。 但是刷新完之后,界面会闪一下。。也没找到是什么原因。。。先记录下来。  

这篇文也描述过这个问题,但是没有说出原因。http://blog.csdn.net/sing_sing/article/details/41046931?utm_source=tuicool


新进展,新进展

首先用tag来标记要删除的哪张图片是比较麻烦而且消耗资源比较多的写法。换成这样就简单多了。

因为button是add在imageview上的,imageview又是add到cell上的,所以先通过superview拿到imageview,再拿到cell。

- (void)deleteBtnClick:(UIButton *)deleteBtn{        UICollectionViewCell *deleteCell = (UICollectionViewCell *)[deleteBtn.superview superview];    NSIndexPath *deleteIndexPath = [_mainView indexPathForCell:deleteCell];        [_photos removeObjectAtIndex:deleteIndexPath.row];    [_mainView deleteItemsAtIndexPaths:@[deleteIndexPath]];    [self resetPhotosView];}

这样写的好处就是,要删除的cell的indexpath肯定是正确的,不像tag标记那样删除图片之后必须刷新走cellForRowAtIndexPath方法才能更新tag。

deleteItemsAtIndexPaths会刷新collectionview,至于为什么没走cellForRowAtIndexPath没搞懂。但是通过cell获取indexPath来对collectionview  delete,move,insert 是最合适的方式。
在知乎上一个大哥这样回答的:
<div>你调用deleteItemsAtIndexPaths方法之后,系统会自动重新刷新界面,但是不会调用cellForItemAtIndexPath,因为没必要,你是删除,不是更改,至于为什么会调用numberOfItemsInSection,是为了重新计算cell的摆放位置(本人推测);</div>
暂时就写到这了。

0 0