OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UICollectionView 中调用 reloadData 后未调用 cellForRowAtIndexPath [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:04
标题: ios - 在 UICollectionView 中调用 reloadData 后未调用 cellForRowAtIndexPath

我有一个 UICollectionView,它使用 UICollectionViewCell 的子类。最初,我的 dataSource 包含 5 个项目,当用户向下滚动时,我获取更多数据并将它们添加到我的 dataSource,然后我调用 reloadData.

但只有 3 个项目可见。当我向上滚动时,我看不到其余的项目,只是一个空白区域。我注意到 cellForRowAtIndexPath 只为这 3 个项目调用。

当我导航到我的父 View 并返回到包含我的 UICollectionView 的 View 时,我可以看到所有项目。

注意:我已经实现了 layout:sizeForItemAtIndexPath 函数,因为每个单元格都有不同的大小。

编辑:

我部分解决了这个问题。我有一个 refreshControl,我在后台线程中调用了 endRefreshing。

我正在添加图片以便更好地演示现在发生的事情:

enter image description here

enter image description here

enter image description here

完成加载新项目后,我调用此方法

- (void)updateDataSource
{
   self.collectionViewDataSource = _manager.messages;
   [self.collectionView reloadData];
}

我检查了 numberOfItemsInSection 方法,它返回正确的项目数。

这是我的布局:sizeForItemAtIndexPath

- (CGSize)collectionViewUICollectionView *)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 仍然处理旧的。



Best Answer-推荐答案


您可能需要使布局无效,以便重新计算单元格位置和高度,因为简单地重新加载数据不会正确设置单元格高度(因为单元格被重复使用)。

- (void)updateDataSource
{
   self.collectionViewDataSource = _manager.messages;
   [self.collectionView reloadData];
   // Add this line.
   [self.collectionView.collectionViewLayout invalidateLayout];
}

关于ios - 在 UICollectionView 中调用 reloadData 后未调用 cellForRowAtIndexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30104037/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4