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.
let label = UILabel()
label.backgroundColor = UIColor.greenColor()
label.text = "Hello,world.\n Just a test."
let font = UIFont.systemFontOfSize(17.0)
label.font = font
label.numberOfLines = 0;
let text = label.text! as NSString
let size = text.sizeWithAttributes([NSFontAttributeName:font])
label.frame = CGRectMake(0, 0, size.width, size.height)
You can use Auto Layout in code. See Auto Layout Guide
The Swift 4.1 extension method to calculate label height:
extension UILabel {
func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
Refer: Adjust UILabel height to text