如何在Swift中以编程方式为UILabel赋予动态高度?
问题描述:
我已使用for循环动态生成的UIlabel,每种类型的diff文本都分配在label中,我想根据文本动态给定UILabel大小.
I have taken UIlabel which are generated dynamically using for loop, each type diff text is assign in label, I want to give UILabel size dynamically depending on text.
在Swift中有什么简单的解决方案吗?
Is there any easy solution in to do that in Swift?
答
let label:UILabel = UILabel(frame: CGRectMake(x, y, width, height))
label.numberOfLines = 4
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
let font = UIFont(name: "Helvetica", size: 20.0)
label.font = font
label.text = "Whatever you want the text enter here"
label.sizeToFit()
如果要根据文本内容设置numberOfLines,请提供最大行数.这在这里非常重要.
If you want to set numberOfLines according to the content of text,give your maximum lines.That is very important here.