【问题标题】:IOS UICollectionView insertItemsAtIndexPaths crash when header is on screen当标题在屏幕上时,IOS UICollectionView insertItemsAtIndexPaths 崩溃
【发布时间】:2013-02-20 05:22:30
【问题描述】:

我有一个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;
}

【问题讨论】:

    标签: ios crash uicollectionview


    【解决方案1】:

    问题是在日志中说标头不能为 nil。所以在此处提供一些有效的输入,您可以避免崩溃。

    如果标题部分不需要输入,请使用 clearclolor 给它一个视图

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

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

    【讨论】:

    • 我应该使用哪种委托方法?你能给我一些示例代码吗?谢谢!
    • 请输入您的代码...也许我可以指出缺少的内容
    • 你应该在问题本身中添加它。那里有一个编辑选项:) 请按照 SO 方式
    • 提供layout.headerReferenceSize = CGSizeMake(320, 50);的目的是什么
    • layout.headerReferenceSize = CGSizeMake(320, 50);我想在 UICollectionView 上留一些空间来添加其他东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多