【问题标题】:UICollectionView: reload data calls numberOfItemsInSection but not cellForItemAtIndexPathUICollectionView:重新加载数据调用 numberOfItemsInSection 但不是 cellForItemAtIndexPath
【发布时间】:2014-12-07 03:50:07
【问题描述】:

我有一个简单的 UICollectionView。第一次加载视图时,cellForItemAtIndexPath 被调用了 3 次,我看到了三个单元格。

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    NSUInteger count = ([self.results count] > 0 ? [self.results count] : 3);
    NSLog(@"count %lu", (unsigned long)count);
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"cellForItemAtIndexPath called");
    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"TasteCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

但是,后来 self.results 变成了一个包含 5 个元素的数组,我称之为:

[self.collectionView reloadData];

发生这种情况时,会再次调用 numberOfItemsInSection,并且其中的“count”日志语句显示它返回 5。但是,这一次从未调用 cellForItemAtIndexPath,并且 UI 仍然显示第一次加载时的三个单元格。

为什么即使计数发生了变化,单元格的数量也没有更新?

【问题讨论】:

  • 也许这个答案可能会有所帮助:stackoverflow.com/a/19100840/2274694
  • UICollectionView & UITableView 只更新视图中的可见单元格。
  • 如果我尝试 Lyndsey 的建议,它会抱怨我在没有插入和删除项目的情况下更改了计数:'NSInternalInconsistencyException',原因:'无效更新:第 0 节中的项目数无效。项目数更新后包含在现有节中的项目数 (5) 必须等于更新前该节中包含的项目数 (3),加上或减去从该节插入或删除的项目数(0 插入,0 删除)加上或减去移入或移出该部分的项目数(0移入,0移出)。'
  • 我去看看 performBatchUpdates 清除数据源并插入新内容

标签: ios objective-c uicollectionview


【解决方案1】:

我想,可能是你使用了静态集合视图单元的概念。 如果它是静态的,请在您的 xib/Storyboard 中将其更改为动态。

【讨论】:

    【解决方案2】:

    尝试再次为 UICollectionView 设置数据源和委托,然后再次重新加载。

    -(void)reloadCollectionView {
      mycollectionView.dataSource = self;
      mycollectionview.delegate = self;
      [mycollectionview reloadData];
    }
    

    【讨论】:

    【解决方案3】:

    请检查您是否已将 collectionView 的数据源和委托连接到您的视图控制器。 如果不这样做

            -(void)viewDidLoad
              {
                  [super viewDidLoad];
                   mycollectionView.dataSource = self;
                   mycollectionview.delegate = self;
              }
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2016-06-05
      • 1970-01-01
      相关资源
      最近更新 更多