Invalid update: invalid number of items on UICollectionView

前端 未结 7 997
攒了一身酷
攒了一身酷 2020-12-07 21:07

I am stumped on this. Here is my scenario. In my Appdelegate, I am creating

  1. An instance of a view controller that will be presented modally to collect two pi
7条回答
  •  -上瘾入骨i
    2020-12-07 21:19

    1. As the collectionView reload data asynchronously, when you call [collectionView reloadData] method, the dataSource may be reloaded after a while. you can call [collectionView layoutIfNeeded] to force the collectionView reload at once.
    2. And when you call [collectionView insertItemsAtIndexPaths:@[indexPaths...]] upon [collectionView reloadData], sometimes the number Of items maybe not equal, you can call [collectionView numberOfItemsInSection:] as a trick before call [collectionView insertItemsAtIndexPaths:@[indexPaths...]].
    3. when the dataSource is empty, the insertion will crash, you should call [collectionView reloadData] instead of [collectionView numberOfItemsInSection:]

    As the above, to avoid this issue, you can do this:

    1. when reload collectionView:
    
        [self.collectionView reloadData];
        [self.collectionView layoutIfNeeded];
    
    2. when invoke the batch updates:
    
        [self.collectionView performBatchUpdates:^{
            ...
            [self.dataSource addDataSource:moreDatas];
    
            NSMutableArray *addIndexPaths;
            ...
    
            if (self.dataSource.count == 1 ||
                [self.collectionView numberOfItemsInSection:0] == self.dataSource.count){
                [self.collectionView reloadData];
            }else{
                [self.collectionView insertItemsAtIndexPaths:addIndexPaths];
            }
        } completion:^(BOOL finished) {}];
    
    

提交回复
热议问题