在集合视图的 performBatchUpdates 崩溃

crashing at performBatchUpdates of collection view

我有一个集合视图,它显示两个具有不同部分计数的图像数组,这将在一个集合视图视图的两个不同视图之间切换

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.storyview)
    {
        return 4;
    }
    else
    {
        return 1;
    }
}

我在哪里执行集合视图的批量更新。它正在崩溃,因为我有两个节数

[self.collectionView performBatchUpdates:^{
        NSRange range = NSMakeRange(0, [self.collectionView numberOfSections]);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.collectionView deleteSections:indexSet];
        [self.collectionView insertSections:indexSet];

    }
                   completion:^(BOOL finished) {
                       [self.collectionView reloadData];
                   }];

我的崩溃日志如下:

 Assertion failure in -[UICollectionView _endItemAnimations], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UICollectionView.m:3901
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections.  The number of sections contained in the collection view after the update (4) must be equal to the number of sections contained in the collection view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).'

谁能告诉我如何避免这种情况?

如日志中所述,您必须确保删除和插入的部分数量与数据源相匹配,而在您的情况下,不匹配。因此,以下是您要查找的内容,

- (void)viewDidLoad {
    [super viewDidLoad];
    self.numSection = 4;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.numSection;
}

- (IBAction)onButton:(id)sender
{
    NSIndexSet *indexSet0 = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,0)];
    NSIndexSet *indexSet123 = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1,3)];

    self.numSection = ( self.numSection==1 ) ? 4 : 1;

    [self.collectionView performBatchUpdates:^{
        // No matter what it is, you need to compute the number of cells 
        // that you need to reload, insert, delete before hand

        // Reload the first section
        [self.collectionView reloadSections:indexSet0];

        if ( self.numSection==4 ) {
            // Insert section 1, 2, 3
            [self.collectionView insertSections:indexSet123];
        } else {
            // Delete section 1, 2, 3
            [self.collectionView deleteSections:indexSet123];
        }
    }
                                  completion:^(BOOL finished) {
                                      // You don't need to do anything here
                                  }];
}