Auto-size label to fit text
suggest changeThis example shows how a label’s width can automatically resize when the text content changes.

Pin the left and top edges
Just use auto layout to add constraints to pin the left and top sides of the label.

After that it will automatically resize.
Notes
- This example comes from this Stack Overflow answer.
- Don’t add constraints for the width and height. Labels have an intrinsic size based on their text content.
- No need to set
sizeToFit
when using auto layout. The complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myLabel: UILabel!
@IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
- This method can also be used to correctly space multiple labels horizontally as in this example.

- If you want your label to line wrap then set the number of lines to 0 in IB and add
myLabel.preferredMaxLayoutWidth = 150 // or whatever
in code. (The button is also pinned to the bottom of the label so that it will move down when the label height increased.)

Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents