获取具有多行的UILabel的垂直大小?

时间:2015-05-31 15:28:53

标签: 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()中完成了上述所有命令。

如何在屏幕上显示正确的标签尺寸?

1 个答案:

答案 0 :(得分:1)

你不需要计算高度,标签知道了它的高度,

    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
    }
相关问题