Issues inserting into UICollectionView section which contains a footer

痴心易碎 提交于 2019-12-03 06:29:24

The answer provided by VaporwareWolf is a bit of a hack. By returning a tiny size instead of a zero size, the supplementary view will always exist but at a size too small to see. So that's why it fixes the NSInternalInconsistencyException

But, there is a real solution.

After adding the data to the datasource and before calling insertItemsAtIndexPaths, just invalidate the layout on the collectionview to make it aware of the changes.

Objective-C

[self.collectionView.collectionViewLayout invalidateLayout]

Swift

collectionView.collectionViewLayout.invalidateLayout()

It turns out that I was actually experiencing a problem with layout (as the error description suggests)

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if(<myDecision>){
        return CGSizeZero;
    } else {
        return CGSizeMake(320, 50);
    }
}

CGSizeZero is what was causing the crash. Instead use CGSizeMake(0.001, 0.001). That's the only change that was necessary. It runs as intended now.

There is a huge article in Russian about bugs in UICollectionView: http://habrahabr.ru/post/211144/.

Here are a couple of methods from that article that may solve your problem:

@try {
    [self.collectionView insertItemsAtIndexPaths:indexPaths];
}
@catch (NSException *exception) {}

or

[self.collectionView performBatchUpdates:^{
        [self.collectionView reloadData];
    } completion:nil];

You should implement both (Header and Footer) methods. Even if you want only one. Look at my code

-(UICollectionReusableView *) collectionView:(UICollectionView *) collectionView
           viewForSupplementaryElementOfKind:(NSString *) kind
                                 atIndexPath:(NSIndexPath *) indexPath
{
    UICollectionReusableView *header = [[UICollectionReusableView alloc] init];

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {

        header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionViewHeader" forIndexPath:indexPath];
    }
    else {
        header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CollectionViewHeader" forIndexPath:indexPath];
    }

    return header;
}

-(CGSize) collectionView:(UICollectionView *) collectionView
                         layout:(UICollectionViewLayout *) collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger) section
{
    return CGSizeMake(self.view.frame.size.width, 100);
}

-(CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!