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.
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()
If you want to set numberOfLines according to the content of text,give your maximum lines.That is very important here.
get a label height depending on it's text, font, and width you assign to it:
func rectForText(text: String, font: UIFont, maxSize: CGSize) -> CGSize {
let attrString = NSAttributedString.init(string: text, attributes: [NSFontAttributeName:font])
let rect = attrString.boundingRectWithSize(maxSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
let size = CGSizeMake(rect.size.width, rect.size.height)
return size
}
let labelSize = rectForText("your text here", font: UIFont.systemFontOfSize(your font), maxSize: CGSizeMake(your label width,999))
let labelHeight = labelSize.height //here it is!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With