I have an UICollectionView
with a header of size non-zero. It seems whenever insertItemsAtIndexPaths
is called, if the header is on screen, the program crashes with the following message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: object cannot be nil (key: <_UICollectionViewItemKey: 0xa38c910> Type = SV Kind = UICollectionElementKindSectionHeader IndexPath = <NSIndexPath 0xa38c7c0> 2 indexes [0, 0])'
When the header size is zero, or when the header is not on screen, calling insertItemsAtIndexPaths
works fine. Does anyone know how to fix this? Thanks!
The class is a sub class of UICollectionViewController. Here is the code related to UICollectionView:
- (id)init {
// Collection view layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.itemSize = CGSizeMake(100, 100);
layout.headerReferenceSize = CGSizeMake(320, 50); // Left for the switch
layout.minimumInteritemSpacing = 5;
layout.minimumLineSpacing = 5;
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
if (self = [super initWithCollectionViewLayout:layout]) {
// Collection view setup
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ID"];
self.collectionView.frame = CGRectMake(0, -20, 320, 480-20-44-49);
self.collectionView.backgroundView = nil;
self.collectionView.backgroundColor = [UIColor clearColor];
...
}
return self;
}
Then I implemented two delegate methods:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [blogs count];
}
and
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewArg cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionViewArg dequeueReusableCellWithReuseIdentifier:@"ID" forIndexPath:indexPath];
/* Some code to get blogView */
[cell.contentView addSubview:blogView];
return cell;
}
The problem is there said in log that the header cannot be nil.So give some valid input there and you can avoid the crash.
Like if the header section needs no input give it an view with clearclolor
For implementhing the header section you must implement the following datasource method
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With