在UICollectionView中调用reloadData后,不会调用cellForRowAtIndexPath

时间:2015-05-07 14:29:35

标签: ios uicollectionview uicollectionviewcell

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

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

当我导航到我的父视图,然后返回包含我的UICollectionView的视图时,我可以看到所有项目。

注意:我已实施layout:sizeForItemAtIndexPath功能,因为每个单元格的大小不同。

修改

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

添加图片以更好地展示现在发生的事情:

  • 第一张图片是在获取新数据之前,因为您可以看到数据显示完美。

enter image description here

  • 第二个图像是在获取新数据之后,因为你可以看到新项目采用前一个项目的精确高度(旧单元格)并且有一个空白区域,当我向下滚动时我可以看到其余的数据,当我向上滚动时,顶部单元格的高度正确,如第3张图片所示。

enter image description here

enter image description here

我加载完新项目后,我称之为

- (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:

我注意到布局:collectionViewLayoutsizeForItemAtIndexPath:被调用并返回正确的高度,但是cellForItemAtIndexPath仍然处理旧的。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在显示代码之前无法理解。但是,我猜你的数据源没有更新。只需检查一下,您的DataSource应该在reloadData之前获取数据。您可以将一些日志用于检查reloadData之前/之后的项目数。这可能有所帮助。

相关问题