UITableViewCell标签未更新

时间:2014-12-05 18:27:13

标签: ios uitableview

我在这里看过很多帖子,但似乎没什么用。我正在尝试更新在故事板中设置的自定义UITableViewCell标签。我在下载过程中收到更新通知时使用此代码:

NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject];
MyListTableViewCell *cell = (MyListTableViewCell *)[self.tableView cellForRowAtIndexPath:index];
//get the update value then
cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate];

我可以在日志中看到值是正确的,并且更新行上的断点恰好在应该的时候命中,但是标签只在我与单元格交互时更新,或者出于某种原因,在我的几秒后更新下载过程已经完成。

我正在使用AFNetworking并且我的所有IBOutlet都被反复检查过。

如何实时更新单元格?

3 个答案:

答案 0 :(得分:2)

您在tableView重新加载之外调用cellForRowAtIndexPath。这将为您提供重用的单元格或全新的实例,但不会显示当时屏幕上显示的单元格。

您应该拨打reloadRowsAtIndexPaths:withRowAnimation.

您的代码应该有一个dataSource,您可以在其中更新当前尝试更新单元格bottomBabel的位置。

然后你的代码应该是这样的:

self.dataSource.megaBytesDownloaded = megaBytesDownloaded;
self.dataSource.totalDownloadEstimate = totalDownloadEstimate;

NSIndexPath *index = [self.fetchedResultsController indexPathForObject:MyObject];
[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];

然后在您的cellForRowAtIndexPath:方法中,您可以在此时更新单元格的bottomLabel。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Your normal setup code here
    cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", self.dataSource.megaBytesDownloaded, self.dataSource.totalDownloadEstimate];
}

由于您似乎也在使用AFNetworking来观察下载进度,因此您还应该考虑在主线程上抛出视图更新代码。在这种情况下,AFNetworking使用多线程来防止UI中出现任何跳跃或延迟。我建议使用GCD来允许主线程处理更新你的UI代码。

看起来应该是这样的:

dispatch_async(dispatch_get_main_queue(), ^{
    //view update code here.
});

答案 1 :(得分:0)

我不认为以你的方式访问一个单元格是一个好主意。我会建议这个

在你的 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath有以下行

cell.bottomLabel.text = [NSString stringWithFormat:@"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate];

并且在NSIndexPath * index = [self.fetchedResultsController indexPathForObject:MyObject]之后;添加这行代码

[self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone;

希望这有助于

答案 2 :(得分:0)

我会尝试使用:

  - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

而是直接将值分配给表格单元格。