ios8 自动布局:两个 multi-line(可能是 0 行)标签

ios8 autolayout: BOTH multi-line(maybe 0 line) label

我想在一个单元格中显示两个 UILabel(Title, Subtitle)。
标题:多行> 0
for Subtitle: 0 多行 2

这里有一个错误(例如,标题和副标题都是 2 行,单元格的 indexPath.row = 1):
我第一次运行模拟器,标题只显示1行,副标题显示2行。在我滚动 tableView 并返回到第一个 indexPath.row 后,它显示正确!好像是这样的:

第一次:
——————————————————
这是磁贴,它应该显示...

这是副标题,应该显示
2 行。

——————————————————

滚动并返回此单元格后:
——————————————————
这是标题,应该显示
两行。

这是副标题,应该显示
2 行。

——————————————————

我做了什么:
在控制器中:
tableView.estimatdRowHeight = 79
tableView.rowHeight = UITableViewAutomaticDimension

在情节提要中:
对于标题:

  1. 将space引导至superview
  2. 尾随 space 到超级视图
  3. 顶部 space 到 Superview
  4. 前导与副标题对齐
  5. 将尾部与副标题对齐
  6. 底部 space 到副标题

副标题:

  1. 底部 space 到超级视图
  2. 将行首与标题对齐
  3. 将尾部与标题对齐
  4. 前space到标题

我为这个错误困惑了好几天,有什么解决办法吗?非常感谢!!!(抱歉缺少图像,因为我没有获得足够的声誉 >><)

从故事板加载的单元格的初始宽度不正确。

这就是为什么标签第一次大小不正确,但在您(重新加载数据,或)将单元格滚动到屏幕外,然后又在屏幕上时正确显示的原因。

由于单元格宽度最初不正确,标签最终使用了比 table 更宽的 preferredMaxLayoutWidth。 (标签认为它有更多空间可以将所有内容放在一条线上。)

对我有用的解决方案是确保我的(子类)单元格的宽度与 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];

    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];

    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, along with his sample code。当我遇到您遇到的相同问题时,这就是让我想到解决方案的原因。