ios - 获取多行的 UILabel 的垂直尺寸?

标签 ios swift uilabel

我有一个不止一行的 UILabel:

let serviceDescription: UILabel = UILabel() serviceDescription.text =
"some very long text..." 
serviceDescription.numberOfLines = 0
serviceDescription.sizeToFit()
self.contentView.addSubview(serviceDescription)

然后我添加一些自动布局约束:

serviceDescription.snp_makeConstraints { (make) -> Void in
  make.top.equalTo(self.contentView_snp_top).offset(24)
  make.left.equalTo(self.contentView).offset(20)
  make.right.equalTo(self.contentView).offset(-20)
}

现在我想计算这个标签在屏幕上需要的大小,所以我做了:

let newSize: CGSize = serviceDescription.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
println("serviceDescription size: \(newSize)")

结果是:

(3408.0, 95.5)

我在 viewDidLoad() 中执行了所有前面的命令。

如何在屏幕上获得正确尺寸的标签?

最佳答案

你不需要计算高度,标签在它自己布局后就知道它的高度,

    override func viewDidLoad() {
        super.viewDidLoad()
        println(label.frame.height) // 21
        label.text = "Some long text to make the text go over more than one line"
        label.layoutIfNeeded()
        println(label.frame.height) // 101.5
    }

关于ios - 获取多行的 UILabel 的垂直尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559157/

相关文章:

ios - 重新定义“SWIFT_NORETURN”宏

java - 如何在 Label JavaFX 中添加多行

android - RIM OS (BIS)、IOS和android中Push功能的区别

Swift 包管理器,如何处理固定装置?

swift - UITextField - 如果文本字段包含某些单词,则不发送到 firebase

iphone - 设置UILabel背景颜色会导致应用崩溃

ios - 动态 UILabel 截断文本

ios - 如何在 UITableViewCell 上显示数组数据?

ios - UIScrollView 以编程方式滚动

javascript - 在 Safari 中使用 PHP 清除 Cookie 的行为很奇怪