我有一个不止一行的 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/