ios8 autolayout:BOTH多行(可能是0行)标签

Ozz*_*hen 3 uitableview autolayout ios8

我想在一个单元格中显示两个UILabel(Title,Subtitle).
为标题:多个线> 0
为字幕:0 多个线 2

这里的一个错误(比如说,标题和副标题都2行,单元格的indexPath.row = 1):
我第一次运行模拟器,标题仅示出了1行和副标题显示2行.滚动tableView并返回第一个indexPath.row后,它显示正确!看起来像这样:

第一次:
-----------------
这是瓷砖,它应该显示......

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

-----------------

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

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

-----------------

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

在故事板中:
对于标题:

  1. 领先的超视空间
  2. 尾随空间到superview
  3. Superview的顶层空间
  4. 对齐导致字幕
  5. 将尾随对齐到字幕
  6. 字幕的底部空间

副标题:

  1. 底层空间到superview
  2. 与标题对齐
  3. 将尾随对齐标题
  4. 标题的顶部空间

我好几天都对这个bug感到困惑,有什么想法可以解决这个问题吗?非常感谢!!!(抱歉缺少图像因为我没有得到足够的声誉> <)

小智 7

从故事板加载的单元格不会以正确的初始宽度开始.

这就是为什么标签第一次没有正确调整大小,但是一旦你(重新加载数据)或者在屏幕外滚动单元格然后在屏幕上正确显示.

由于单元格宽度最初不正确,因此标签最终使用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;
}
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

我还建议查看smileyborg 关于自我调整细胞优秀答案,以及他的示例代码.当我碰到你遇到的同一个问题时,这就是解决方案的原因.