【问题标题】:Get height of auto-layout cell with wrapped text in it获取包含文本的自动布局单元格的高度
【发布时间】:2015-01-16 06:55:41
【问题描述】:

我正在尝试实现 heightForRowAtIndexPath 并希望使用我已经布局的具有自动布局的原型单元来查找高度。我已经尝试了以下所有方法,但都没有给我单元格的实际高度。他们似乎在标签被换行之前给了我单元格的高度。

我知道我可以使用 NSString 方法来查找每个字符串的高度并以这种方式计算单元格的高度,但是如果我沿着这条路走,我基本上是在复制自动布局的功能,并且必须维护单元格的布局在两个地方。我真的很想避免这种情况,我假设我在这里遗漏了一些非常简单的东西。

我的原型单元格的高度在 IB 中设置为 67,而内容视图的高度在 IB 中设置为 66。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"in heightForRowAtIndexPath: %@", indexPath);

    if (!self.prototypeCell)
    {
        self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"MessageCell"];
    }

    // set the text in the labels
    [self configureCell:self.prototypeCell forIndexPath:indexPath isForOffscreenUse:YES];

    [self.prototypeCell setNeedsLayout];
    [self.prototypeCell layoutIfNeeded];

    // this gives 58 regardless of the length of the text in my labels
    CGSize contentViewSize = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    // this gives me 58.5 regardless of the length of text in my labels
    CGSize cellSize = [self.prototypeCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    return cellSize.height;
}

【问题讨论】:

标签: ios interface-builder autolayout


【解决方案1】:

我通过设置标签的首选宽度解决了这个问题:

// the label is inside the table view 8 points from each edge
messageCell.message.preferredMaxLayoutWidth = tableView.frame.size.width - 16;

【讨论】:

    猜你喜欢
    • 2014-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    相关资源
    最近更新 更多