如何将 preferredMaxLayoutWidth 用作我的 UILabel 的自动设置并找出其视图的高度?

How do I use preferredMaxLayoutWidth as automatic for my UILabel and find out the height of its view?

在 iOS 8 中,您似乎可以将 UILabels 设置为具有自动的 preferredMaxLayoutWidth,这只是通过自动布局计算出来的。但是,我似乎无法弄清楚如何计算标签所在视图的高度。基本上我有一个多行 UILabel 固定在 UIView 的两侧,我想知道 UIView 有多高。 (在本例中它是一个单元格。)

如果我写:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyTableViewCell
    cell.label1.text = "some sample text to test it out, and it resolves to two lines long"
    let height = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height

    return height + 1.0 // Extra 1.0 is for separator height
}

单元格的高度始终是 UILabel 只有一行长时的高度。我将 numberOfLines 设置为 0,因此对于多行性质,它应该返回一个更大的数字。 systemLayoutFittingSize 调用显然在这里不起作用。

我做错了什么?

通过将内容拥抱优先级设置为高于高度约束优先级的值,您始终可以驻留在自动版式上。或者您可以使用以下代码计算适合的高度。

CGSize sizeThatFits = [YourString boundingRectWithSize:CGSizeMake(yourDesiredWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;

编辑: 您有约束优先级。这意味着在发生冲突时每个约束都有优先级。更高的优先级意味着它将首先被满足。您只需要将内容的优先级设置为高于正常高度限制即可。