是的。这实际上是一个自我调整大小的问题,您需要解决它,直到它被修复。
问题是当一个单元被实例化时,它的初始宽度是基于故事板的宽度。由于这与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;
}
我还建议您查看smileyborg 的excellent answer about self-sizing cells,以及他的sample code。当我遇到与您遇到的相同问题时,这就是让我找到解决方案的原因。
更新:
configureCell:forRowAtIndexPath: 是 Apple 在其示例代码中使用的一种方法。当您有多个tableViewController 时,通常将其子类化,并在每个视图控制器中分解特定于控制器的cellForRowAtIndexPath: 代码。超类处理公共代码(例如使单元格出列),然后调用子类,以便它可以配置单元格的视图(因控制器而异)。如果您不使用子类化,只需将该行替换为特定代码即可设置单元格的(自定义)属性:
cell.textLabel.text = ...;
cell.detailTextLabel.text = ...;