iosxcodeswiftuilabelsizetofit

Xcode - Swift - UILabel height expanding for text


I want to make a UILabel's height expand depending on its text.

Here is what the view controller looks like, with the label selected:

enter image description here

Here is the code (I have tried a bunch of different similar things but this is what I have right now):

import UIKit

class ViewControllerTEST: UIViewController {

@IBOutlet weak var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()


    label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), 0)
    label.numberOfLines = 0
    label.lineBreakMode = .ByWordWrapping
    label.text = "This is a really\nlong string"
    label.setNeedsLayout()
    label.sizeToFit()
    label.frame = CGRectMake(0, 0, CGRectGetWidth(label.bounds), CGRectGetHeight(label.bounds))



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

And, as you can see here, it doesn't work as intended:

enter image description here


Solution

  • Don't use a frame, use autolayout. Add a top, leading, and trailing constraint to the label (I would suggest doing this in the storyboard). As long as you have lines equal to 0 (which you do), the height will adjust automatically. If you want to add the constraints in code, your viewDidLoad would look something like this:

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = "This is a really\nlong string"
        label.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addSubview(label)
        let views = ["label": label]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: nil, metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]", options: nil, metrics: nil, views: views))
    }