【发布时间】: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