This example shows how a label's width can automatically resize when the text content changes.
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
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" } }
myLabel.preferredMaxLayoutWidth = 150 // or whateverin code. (The button is also pinned to the bottom of the label so that it will move down when the label height increased.)