iOS Size to fit


Example

Suppose you have a UILabel on your storyboard and you have created an IBOutlet for it in ViewController.swift / ViewController.m and named it labelOne.

To make the changes easily visible, change the backgroundColor and textColor of labelOne in the viewDidLoad method:

The function sizeToFit is used when you want to automatically resize a label based on the content stored within it.

Swift

labelOne.backgroundColor = UIColor.blueColor()
labelOne.textColor = UIColor.whiteColor()
labelOne.text = "Hello, World!"
labelOne.sizeToFit()

Swift 3

labelOne.backgroundColor = UIColor.blue
labelOne.textColor = UIColor.white
labelOne.text = "Hello, World!"
labelOne.sizeToFit()

Objective-C

labelOne.backgroundColor = [UIColor blueColor];
labelOne.textColor = [UIColor whiteColor];
labelOne.text = @"Hello, World!";
[labelOne sizeToFit];

The output for the above code is:

enter image description here

As you can see, there is no change as the text is perfectly fitting in labelOne. sizeToFit only changes the label’s frame.

Let’s change the text to a slightly longer one:

labelOne.text = "Hello, World! I’m glad to be alive!"

Now, labelOne looks like this:

enter image description here

Even calling sizeToFit doesn't change anything. This is because by default, the numberOfLines shown by the UILabel is set to 1. Let’s change it to zero on the storyboard:

enter image description here

This time, when we run the app, labelOne appears correctly:

enter image description here

The numberOfLines property can also be changed in the ViewController file :

// Objective-C
labelOne.numberOfLines = 0; 

// Swift
labelOne.numberOfLines = 0