延迟图像下载完成后更新 UITableViewCell

2024-05-14

异步下载单元格图像后,我在更新 UITableViewCells 时遇到一些问题。我正在使用自定义 UITableViewCells,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"productCell";
    MainTableViewCell *cell = (MainTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[MainCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"] autorelease];
    }
}

我有一个 UITableViewCell 类,然后是一个完成所有绘图的类。这是来自 Apple 的示例代码,名为“AdvancedTableViewCells”,我正在执行复合操作。

我的单元格中有图像,我使用 Apple 名为“LazyTableImages”的示例代码异步下载这些图像。这是应该更新单元格的委托:

- (void)coverImageDidLoad:(NSIndexPath *)indexPath {
    CoverImageAsyncLoader *coverImageAsyncLoader = [imageDownloadsInProgress objectForKey:indexPath];
    if (coverImageAsyncLoader != nil) {
        MainTableViewCell *cell = (MainTableViewCell *)[self.tableView cellForRowAtIndexPath:coverImageAsyncLoader.indexPathInTableView];

        // Display the newly loaded image
  if (coverImageAsyncLoader.products.coverImage != nil) {
   cell.productCover = coverImageAsyncLoader.products.coverImage;
  } else {
   cell.productCover = blankCoverImage;
  }
    }
}

但什么也没发生。一位朋友告诉我,我无法从后台线程更新 UI,但由于我是通过委托执行此操作,所以我不确定为什么它不更新。我努力了:

 [cell setNeedsDisplay];
 [cell.contentView setNeedsDisplay];

并将单元格设置为:

 cell = [[[MainCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"productCell"] autorelease];

然后更新单元格的显示。

但没有任何效果:(我可以发布更多代码,但帖子已经有点长了。


如果您知道相关单元格的索引路径的行和部分(例如myCellIndexPath.section and myCellIndexPath.row),看看重新加载UITableView带有表视图的单元格-reloadRowsAtIndexPaths:withRowAnimation:方法。

例如:

[tableView beginUpdates];
NSUInteger _path[2] = {myCellIndexPath.section, myCellIndexPath.row};
NSIndexPath *_indexPath = [[NSIndexPath alloc] initWithIndexes:_path length:2];
NSArray *_indexPaths = [[NSArray alloc] initWithObjects:_indexPath, nil];
[_indexPath release];
[tableView reloadRowsAtIndexPaths:_indexPaths withRowAnimation:UITableViewRowAnimationRight];
[_indexPaths release];
[tableView endUpdates];

当这更新 UI 时,您将需要在主线程上运行的方法中进行此操作。

还有其他行动画,取决于口味(UITableViewRowAnimationFade, UITableViewRowAnimationNone, ETC。)。在以下位置搜索您的帮助UITableViewRowAnimation struct.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

延迟图像下载完成后更新 UITableViewCell 的相关文章

随机推荐