iOS常见问题ios专题iOS开发

[UICollectionView _endItemAnimat

2016-03-14  本文已影响3791人  萌小菜

今天coding的时候出现了如题那个bug,在网上找了找没有找到具体的解决方法,不过大神们也给出了了问题原因方向:

- (void)insertItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;

分析(可以忽略直接看最后)

    [self.userInfos insertObject:info atIndex:0];
    [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];

由于数据源方法是异步的,在此之前还没有调用数据源方法numberOfItemsInSection,所以此时collectionView并不知道自身有多少个cell(或者说collectionView的cell还没有创建出来),也就无法进行cell的添加删除和刷新,所以会提示InvalidationContext

解决方法

延时调用insertItemsAtIndexPaths方法,也就是在collectionView调用完数据源方法后再进行cell的操作。一定要这样写(时间自己设定)

或者让collectionView主动调用一次据源方法,知道自己有多少个cell后才能操作cell,这样写:
(2016.9.21更新)

由于此问题出现的概率不大,所以对于测试问题解决方式来说有很多不确定性。之前的方法我本以为彻底解决了问题,没想到上线后同样的问题又出现了,很是无奈,只好另外再找解决方法,使用下面方法到现在基本上没有再出崩溃的问题,大家可以参考测试:

[self.infos removeLastObject];
if ([self.collectionView numberOfItemsInSection:0] == self.infos.count) {
      [self.collectionView reloadData];
}else{
      [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:self.infos.count-1 inSection:0]]];
 }
[self.infos insertObject:info atIndex:0];
    
if (self.infos.count == 1 || [self.collectionView numberOfItemsInSection:0] == self.infos.count) {
        [self.collectionView reloadData];
}else{
        [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:0 inSection:0]]];
}

说明

完成

上一篇下一篇

猜你喜欢

热点阅读