UITableViewCell textLabel, does not update until a scroll, or touch happens, while using GCD

隐身守侯 提交于 2019-12-03 10:56:51

It seems that just setting the text of the cell is not enough for it to be refreshed. Have you tried putting [cell setNeedsDisplay] after setting the text and see what happens? BTW, since you are already using GCD to compute stuff in the background you should try to avoid doing any work at all on the main queue. I would write that piece of code more like:

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];
});
Nisarg Shah

You seem to be updating the cell on another thread (which is not the main thread)

Try this when you reload the tableview:

Objective-C

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});

Swift

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}

I guess that GCD running your block in main thread with default run loop mode. Try another way:

- (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]];
        NSString *time      = [data objectForKey:@"Time"];
        NSString *totalTime = [data objectForKey:@"Total Time"];
        NSString *textLabel  = [NSString stringWithFormat:@" %@ %@", time, totalTime];

        [cell performSelectorOnMainThread:@selector(setText:) withObject:textLabel waitUntilDone:NO modes:@[NSRunLoopCommonModes]]; //instead of using literals you could do something like this [NSArray arrayWithObject:NSRunLoopCommonModes];
    });

    return cell;
}

In swift 5

    DispatchQueue.main.async() {
        self.listView.reloadData()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!