Search code examples
swiftuilabelsizetofit

Set height for a variable length message into a UIlabel in swift is not correct always


I wrote the following lines of code to set a variable length message into a UIlabel in swift, which works properly 9 out of 10 times. But at one time it suddenly truncated the last 2 or 3 lines from the message:

var response: AnyObject = prefs.objectForKey("response")!
response = response.stringByReplacingOccurrencesOfString("-", withString: "\n")
msglbl.numberOfLines = 0;
msglbl.text = "\(response)"  

msglbl.textAlignment = .Center;
msglbl.sizeToFit()
self.view.addSubview(msglbl)
msglbl.font = UIFont(name: "Gotham-Book", size: 16)

Please let me know what I am doing wrong.


Solution

  • You are calling sizeToFit() before setting the label's font and size. Thus the label is being sized for the wrong font and size. Configure everything about the label first. Then size it to fit that configuration.