UITableViewCell需要reloadData()来调整高度

我有一个应用约束的自定义表格单元格,但第一次显示表格行高不正确调整,除非新的单元格创build,有没有办法做到这一点,而无需再次调用reloadData?

是。 这实际上是一个自我调整的问题,你需要解决,直到它被修复。

问题是当一个单元格被实例化时,其初始宽度基于故事板宽度。 由于这与tableView宽度不同,初始布局错误地确定了内容实际需要的行数。

这就是为什么第一次内容的大小不正确,但是一旦你重新加载数据,或者将单元格滚动到屏幕外,然后在屏幕上,就会正确显示。

您可以通过确保单元格的宽度与tableView宽度匹配来解决此问题。 您的初始布局将是正确的,无需重新加载tableView:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; [cell adjustSizeToMatchWidth:CGRectGetWidth(self.tableView.frame)]; [self configureCell:cell forRowAtIndexPath:indexPath]; return cell; } 

在TableViewCell.m中:

 - (void)adjustSizeToMatchWidth:(CGFloat)width { // Workaround for visible cells not laid out properly since their layout was // based on a different (initial) width from the tableView. CGRect rect = self.frame; rect.size.width = width; self.frame = rect; // Workaround for initial cell height less than auto layout required height. rect = self.contentView.bounds; rect.size.height = 99999.0; rect.size.width = 99999.0; self.contentView.bounds = rect; } 

我还build议检查一下smileyborg 关于自定义单元格的优秀答案 ,以及他的示例代码 。 当我碰到你遇到的同样的问题时,这就是我解决问题的方法。

更新:

configureCell:forRowAtIndexPath:是Apple在示例代码中使用的一种方法。 当你有多个tableViewController ,通常会对它进行子类化,并在每个视图控制器中分解出特定于控制器的cellForRowAtIndexPath:代码。 超类处理公共代码(如出队单元),然后调用子类,以便可以configuration单元的视图(从控制器到控制器)。 如果您不使用子类化,只需将该行replace为特定代码即可设置单元格的(自定义)属性:

  cell.textLabel.text = ...; cell.detailTextLabel.text = ...;