重新排列部分之间的项目时,UICollectionView崩溃

我在UICollectionView部分之间有animation变化的麻烦,我的程序不断崩溃,有什么问题呢?

我有一个收集视图,它有四个部分:

0:A
1:B
2:C
3:D

我想把它变成只有三个部分具有相同的项目:

0:A
1:B,C
2:D

而且我想要让这个转变成为animation:

 // Initial state NSArray *source = @[ @[@"A"], @[@"B"], @[@"C"], @[@"D"] ]; // Some data source methods - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return [source[section] count]; } - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return [source count]; } // Transformation: that works but I have to keep an empty section source = @[ @[@"A"], @[@"B", @"C"], @[@"D"], @[] ]; [collection performBatchUpdates:^{ [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:2] toIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:3] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:2]]; } completion:nil]; // Transformation: that crashes! source = @[ @[@"A"], @[@"B", @"C"], @[@"D"] ]; [collection performBatchUpdates:^{ [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:2] toIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]]; [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:3] toIndexPath:[NSIndexPath indexPathForItem:0 inSection:2]]; [collection deleteSections:[NSIndexSet indexSetWithIndex:3]]; } completion:nil]; 

我一直得到崩溃,或者内部断言失败: Assertion failure in -[UICollectionView _endItemAnimations]... ,或者有时,更奇怪,一个malloc错误: incorrect checksum for freed object...

如果我不调用deleteSections:它也不起作用。 如果我先放,它不会改变任何东西。 如果我删除moveItemAtIndexPath:toIndexPath:具有相同的源和目的地,它不会改变任何东西。 如果我不是在一个批处理块中执行的话,它显然会在第一个命令中崩溃。 我忽略了什么?

从这个非常有趣的文章关于UICollectionView摘录:

在批量更新块中插入新节时,不得在该节中插入任何项目 – 将隐式处理。 实际上,将项目插入到批次更新块中新插入的部分中会创build卡在集合视图图层分层结构中的“重影”图层。 据推测,这是一个UICollectionView只是一个错误,因为这种行为没有logging,并没有引发exception

知道这一点,我觉得删除部分和moveItemFromIndexPath:toIndexPath在一起工作也不奇怪。 我想这是“同样的错误”。

我使用的解决scheme:

我在我应该删除的部分放了一个假的不可见的单元格。 这允许我保持相同的行为,如果我做了moveItemFromIndexPath:toIndexPath: 当然,我相应地调整了我的数据源!

你有没有试过类似的东西:

 source = @[ @[@"A"], @[@"B", @"C"], @[@"D"] ]; [collection performBatchUpdates:^{ [collection moveItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:2] toIndexPath:[NSIndexPath indexPathForItem:1 inSection:1]]; [collection deleteSections:[NSIndexSet indexSetWithIndex:2]]; } completion:nil];