嗨,我正在使用自定义 UICollectionView ( https://github.com/SureCase/WaterfallCollectionView ),一切正常。现在我正在设置从 UICollectionView 中删除项目,并且我可以很好地删除它们。当我尝试删除该部分的最后一项时,问题就出现了。
它给出了以下错误。
*** Assertion failure in -[UICollectionViewData layoutAttributesForSupplementaryElementOfKind:atIndexPath:], /SourceCache/UIKit/UIKit-2935.137/UICollectionViewData.m:787
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForSupplementaryElementOfKind: UICollectionElementKindSectionHeader at path <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}'
我用来删除项目的代码如下:
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
NSLog(@"Erasing Objects!");
//First I remove Items from DataSource, and after from Collection View
[self deleteItemsFromDataSourceAtIndexPaths:selectedIndexes];
[self.cv deleteItemsAtIndexPaths:selectedIndexes];
[selectedIObjectsIndexes removeAllObjects];
[selectedIndexes removeAllObjects];
EditUICollection=NO;
EasyMediaGreenView.hidden = YES;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.7 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self.cv reloadData];
});
}else{
NSLog(@"Not delete");
}
}
因此,我首先从数据源中删除项目,然后从 Collection View 中删除项目。这是从数据源中删除的代码。
-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray *)itemPaths
{
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath in itemPaths) {
[indexSet addIndex:itemPath.row];
}
[idObject removeObjectsAtIndexes:indexSet];
[typeObject removeObjectsAtIndexes:indexSet];
[urlObject removeObjectsAtIndexes:indexSet];
[textObject removeObjectsAtIndexes:indexSet];
}
当所有其他对象都已正确删除时,为什么当我尝试删除最后一个对象时会发生这种情况?我想了解这部分,并且知道如何解决这个问题吗?感谢大家。
最佳答案
我找到了解决办法! 我总是为部分返回 1,因此即使没有任何项目,CollectionView 也会被构建,并要求构建一个 header ,如下所示:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSString *)kind
atIndexPath:(NSIndexPath *)indexPath; {
所以我计算了数据数组中的项目,如果数组为空,则不应该有一个部分。
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
if(idObject.count>0){ return 1; }
else{ return 0; }
}
因此,当我从数据数组中删除项目时,我可以检查数组是否为空,如果不为空,我将删除项目,如果是,我将删除整个部分。
NSLog(@"Erasing Objects!");
[self deleteItemsFromDataSourceAtIndexPaths:selectedIndexes];
if(idShadeInside.count > 0){
[self.cv deleteItemsAtIndexPaths:selectedIndexes];
}
else{
//Creating an IndexSet with the Section to Erase
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];[indexSet addIndex:0];
[self.cv deleteSections:indexSet];
}
问题解决了!
关于ios - 删除 UICollectionView 中的最后一个单元格会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24447065/