UITableViewCell textLabel,在使用GCD时直到滚动或触摸发生时才会更新

nmd*_*ias 19 objective-c uitableview grand-central-dispatch ios

有人可以帮我解决这个问题吗?

我的UITableViewCell textLabel在我滚动触摸之前不会更新.

视图控制器负载,它显示了细胞的适量.但内容是空白的.我必须触摸它或滚动才能显示我的textLabel.

我在这里做错了吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    [[cell textLabel] setFont: [UIFont systemFontOfSize: 32.0]];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSDictionary * data = [self timeForObject: [self.months objectAtIndex:indexPath.row]];

        dispatch_async(dispatch_get_main_queue(), ^{

            NSString *time      = [data objectForKey:@"Time"];
            NSString *totalTime = [data objectForKey:@"Total Time"];

            NSString * textLabel  = [NSString stringWithFormat:@" %@ %@",
                                        time, totalTime];

            [[cell textLabel] setText:textLabel];



        });
    });

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏

谢谢!

努诺

编辑:

对[cell setNeedsLayout]的调用修复了这个问题.谢谢你们每一个人的帮助!

Grz*_*icz 11

似乎只是设置单元格的文本不足以刷新它.您是否[cell setNeedsDisplay]在设置完文本后尝试放置,看看会发生什么?顺便说一句,既然你已经在后台使用GCD来计算东西,你应该尽量避免在主队列上做任何工作.我会写那段代码更像:

NSDictionary *data = [self timeForObject: [self.months objectAtIndex:indexPath.row]];
NSString *time      = [data objectForKey:@"Time"];
NSString *totalTime = [data objectForKey:@"Total Time"];
NSString *textLabel = [NSString stringWithFormat:@" %@ %@", time, totalTime];

dispatch_async(dispatch_get_main_queue(), ^{
    [[cell textLabel] setText:textLabel];
    [cell setNeedsDisplay];
});
Run Code Online (Sandbox Code Playgroud)

  • [cell setNeedsLayout]修好了!=) (8认同)

小智 6

您似乎正在更新另一个线程(不是主线程)上的单元格

重新加载tableview时,请尝试以下操作:

目标C

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});
Run Code Online (Sandbox Code Playgroud)

迅速

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)