Suppose you have a
UILabel on your
storyboard and you have created an
IBOutlet for it in
ViewController.m and named it
To make the changes easily visible, change the
textColor of labelOne in the
sizeToFit is used when you want to automatically resize a label based on the content stored within it.
labelOne.backgroundColor = UIColor.blueColor() labelOne.textColor = UIColor.whiteColor() labelOne.text = "Hello, World!" labelOne.sizeToFit()
labelOne.backgroundColor = UIColor.blue labelOne.textColor = UIColor.white labelOne.text = "Hello, World!" labelOne.sizeToFit()
labelOne.backgroundColor = [UIColor blueColor]; labelOne.textColor = [UIColor whiteColor]; labelOne.text = @"Hello, World!"; [labelOne sizeToFit];
The output for the above code is:
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:
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:
This time, when we run the app, labelOne appears correctly:
numberOfLines property can also be changed in the
ViewController file :
// Objective-C labelOne.numberOfLines = 0; // Swift labelOne.numberOfLines = 0