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.
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 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.)