我的iOS应用程序中有一个UICollectionView。我想使用各种insert ...方法来添加数据,主要是为了使用iOS时提供的动画(而不是reloadData :)。
但是,如果我尝试添加一个部分,我会从iOS获得一个例外。我的代码非常简单:
_regions = [NSMutableArray array];
[self.collectionView reloadData];
NSLog (@"Before attempting to add section, collection view has %ld sections", [self numberOfSectionsInCollectionView:self.collectionView]);
[_regions addObject:@"First Region"];
[self.collectionView insertSections:[[NSIndexSet alloc] initWithIndex:0]];
NSLog (@"After attempting to add section, collection view has %ld sections", [self numberOfSectionsInCollectionView:self.collectionView]);
所以我在我的_regions数组中添加一个对象,我用它来实现数据源,然后调用insertSection。我的第一个NSLog工作:
2015-03-24 11:25:39.052 MyApp[63858:17968323] Before attempting to add section, collection view has 0 sections
然后iOS抛出异常:
2015-03-24 11:25:42.082 MyApp[63858:17968323] *** 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 (1) 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 (1 inserted, 0 deleted).'
我以非常简单的方式实现numberOfSectionsInCollectionView:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return _regions.count;
}
如果我反转调用(在将字符串添加到_regions数组之前调用insertSections),我会得到一个不同的异常:
2015-03-24 11:33:17.472 MyApp[63965:18001840] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert section 0 but there are only 0 sections after the update'
相对于我将部分添加到UICollectionView时,我应该何时修改(添加元素)_regions?
非常感谢经验丰富的UICollectionView程序员提供的任何帮助。 。