当标题在屏幕上时,IOS UICollectionView insertItemsAtIndexPaths崩溃

时间:2013-02-20 05:22:30

标签: ios crash uicollectionview

我的UICollectionView标题大小非零。似乎每当调用insertItemsAtIndexPaths时,如果标题在屏幕上,程序将崩溃,并显示以下消息:

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])'

当标题大小为零时,或标题不在屏幕上时,调用insertItemsAtIndexPaths可以正常工作。有谁知道如何解决这一问题?谢谢!

该类是UICollectionViewController的子类。这是与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;
}

然后我实现了两个委托方法:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
  return [blogs count];
}

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

1 个答案:

答案 0 :(得分:8)

问题是在日志中说标题不能为零。所以在那里给出一些有效的输入,你可以避免崩溃。

如果标题部分不需要输入,请使用clearclolor

给它一个视图

要实现标题部分,必须实现以下数据源方法

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

快乐编码:)