我想在指定行数后以编程方式创建一个 UILabel。我正在使用 swift 。我有以下代码:
let newLabel = UILabel()
newLabel.text = "Hello There"
newLabel.font = UIFont.systemFont(ofSize: 16)
newLabel.numberOfLines = 2
newLabel.lineBreakMode = .byWordWrapping
newLabel.sizeToFit()
newLabel.frame.origin.x = 100
newLabel.frame.origin.y = 500
view.addSubview(newLabel)
问题是标签的文本在一行上,而不是两行。我必须使用 sizeToFit 因为 fontSize 实际上是动态的(它并不总是 16)。如何确保标签是 2 行?谢谢。
最佳答案
您没有指定 UILabel
的确切 frame
。因此您的 View 只会获得它想要的任何宽度。您可以使用它来获取结果:
newLabel.frame = CGRect(x: 100, y: 500, width: newLabel.frame.width - 1, height: newLabel.frame.height * 2)
但这不太好,我建议使用 AutoLayout
关于swift - UILabel SizetoFit 指定行数后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53685843/