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

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

我的UITableViewCell textLabel ,不会更新,直到我滚动 ,或触摸它。

ViewController加载,它显示适量的单元格 。 但内容是空白的。 我必须触摸它或滚动来使我的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; } 

任何帮助表示赞赏

谢谢!

努诺

编辑:

调用[cell setNeedsLayout]可以解决这个问题。 谢谢你们每一个人的帮助!

似乎只是设置单元格的文本是不够的,它被刷新。 你有没有尝试把[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]; }); 

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

尝试这个时重新加载tableview:

Objective-C的

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

迅速

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

我猜GCD在主线程中运行你的块,默认运行循环模式。 尝试另一种方式:

 - (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; } 
Interesting Posts