05Size to fit

suggest change

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:

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:

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:

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

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

// Objective-C
labelOne.numberOfLines = 0; 

// Swift
labelOne.numberOfLines = 0

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


UILabel:
* 05Size to fit

Table Of Contents
1 UILabel
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable