崩溃在集合视图的performBatchUpdates

我有一个集合视图显示两个不同的图像数量的数组这将是一个collectionview视图的两个不同的视图之间切换

- (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 }]; }