【发布时间】:2015-05-07 14:29:35
【问题描述】:
我有一个UICollectionView,它使用UICollectionViewCell 的子类。最初,我的dataSource 包含 5 个项目,当用户向下滚动时,我获取更多数据并将它们添加到我的dataSource,然后我调用reloadData。
但只有 3 个项目可见。当我向上滚动时,我看不到其余的项目,只是一个空白区域。我注意到 cellForRowAtIndexPath 只被调用这 3 个项目。
当我导航到我的父视图并返回到包含我的UICollectionView 的视图时,我可以看到所有项目。
注意:我已经实现了layout:sizeForItemAtIndexPath 函数,因为每个单元格都有不同的大小。
编辑:
我部分解决了这个问题。我有一个 refreshControl,我在后台线程中调用了 endRefreshing。
我正在添加图片以便更好地演示现在发生的事情:
- 第一张图片是在获取新数据之前,您可以看到数据显示完美。
- 第二张图片是在获取新数据之后,您可以看到新项目的高度与之前的项目(旧单元格)完全相同,并且有一个空白区域,当我向下滚动时,我可以看到其余部分数据,当我向上滚动时,顶部的单元格得到正确的高度,如第三张图片所示。
完成加载新项目后,我调用此方法
- (void)updateDataSource
{
self.collectionViewDataSource = _manager.messages;
[self.collectionView reloadData];
}
我检查了 numberOfItemsInSection 方法,它返回正确的项目数。
这是我的布局:sizeForItemAtIndexPath
- (CGSize)collectionView:(UICollectionView *)collectionView layout: (UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath: (NSIndexPath *)indexPath
{
// Here I am calculating the width and height of the textView which will fit the message
SPH_PARAM_List *feed_data=[[SPH_PARAM_List alloc]init];
feed_data=[self.collectionViewDataSource objectAtIndex:indexPath.row];
if ([feed_data.chat_media_type isEqualToString:kSTextByme]||[feed_data.chat_media_type isEqualToString:kSTextByOther])
{
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:feed_data.chat_message];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
[calculationView setFont:[UIFont systemFontOfSize:14]];
[calculationView setTextAlignment:NSTextAlignmentJustified];
CGSize sc = [calculationView sizeThatFits:CGSizeMake(TWO_THIRDS_OF_PORTRAIT_WIDTH, CGFLOAT_MAX)];
NSLog(@"IndexPath: %li Height: %f", (long)indexPath.row ,sc.height);
return CGSizeMake(self.view.frame.size.width - (5 * 2), sc.height);
}
return CGSizeMake(self.view.frame.size.width - (5 * 2), 90);
}
编辑 2:
我注意到 layout:collectionViewLayoutsizeForItemAtIndexPath: 被调用并返回正确的高度,但 cellForItemAtIndexPath 仍然处理旧的。
【问题讨论】:
-
不是
cellForItemAtIndexPath的方法吗? -
用相关代码更新您的问题,以便我们指出问题。
-
@rmaddy 我已经更新了我的问题并添加了一些相关代码,你需要我添加更多吗?
-
您是否尝试过使布局无效?由于顶部单元格需要重新加载和调整大小,您可能需要在数据更改时调用
[collectionView.collectionViewLayout invalidateLayout];,因为重复使用的单元格必须重新确定高度 -
只是一个建议:当我看到这样的问题时,它们通常是由于没有从主队列调用 UI Kit 引起的。确保在主队列上分派所有呼叫。
dispatch_async(dispatch_get_main_queue(), ^{ ... do stuff
标签: ios uicollectionview uicollectionviewcell