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

标签 ios objective-c uitableview cocoa-touch ios8

在 iOS 8 中,您似乎可以将 UILabel 设置为具有自动的 preferredMaxLayoutWidth,这只是通过自动布局计算出来的。但是,我似乎无法弄清楚如何计算标签所在 View 的高度。基本上我有一个多行 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;

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

enter image description here

关于ios - 如何将 preferredMaxLayoutWidth 用作我的 UILabel 的自动设置并找出其 View 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28791533/

相关文章:

ios - 计算所有尺寸的iphone的纵横比

ios - 检查PHFetchResult中是否存在PHAsset

ios - 使用 UITableView 嵌入 UIScrollView

ios - 使用静态单元格本地化 UITableView 部分中标题的标题

ios - 容器 View 集合 VC 被父级的点击手势识别器阻止

iphone - IOS 中是否存在用于 UI 控件自动化的现有库

iphone - 如何更改图像中的特定颜色?

iphone - 滚动范围可见 : How to scroll to the beginning of an UITextView

ios - 像 Twitter 应用一样展开表格 View 单元格

ios - (Apple) GameplayKit State Machine implementation with SKScene