我已经以编程方式为UIView添加了一个Label。但是,根据Label中的文字,我似乎无法使其自动调整大小。我已尝试使用此扩展程序,但我不确定如何正确使用它
extension UILabel {
func resizeHeightToFit(heightConstraint: NSLayoutConstraint) {
let attributes = [NSFontAttributeName : font]
numberOfLines = 0
lineBreakMode = NSLineBreakMode.ByWordWrapping
let rect = text!.boundingRectWithSize(CGSizeMake(frame.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
heightConstraint.constant = rect.height
setNeedsLayout()
}
}
然后我尝试了这个:
titleLabel?.resizeHeightToFit(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: titleLabel!.frame.height))
但它会返回错误。
答案 0 :(得分:1)
您可以尝试sizeToFit()
:
let label = UILabel()
label.text = "Text"
label.sizeToFit()
print(label.frame) // "(0.0, 0.0, 32.5, 20.5)"
label.text = "Text that is pretty long this time"
label.sizeToFit()
print(label.frame) // "(0.0, 0.0, 241.5, 20.5)"