Make UILabel Adjust Width to Fit Text

In this tutorial, you will learn how to make UILabel automatically adjust its width to make the text fit. When the text on UILabel is longer than the width of the UILabel it does not fit. Below is an example of a UILabel with a text that does not fit.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

When Text Does Not Fit on Label

UILabel text does not fit

Make UILabel Fit Text

To make UILabel adjust its width to fit the text, I will use auto-layout constraints. I will select UILabel on the view and will add two new constraints: Top and Leading constraints.

Add new UILabel Constraints

Now with the two new constraints added, I can open Swift code editor and set a longer text to UILabel.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!
    override func viewDidLoad() {
        myLabel.backgroundColor = UIColor.yellow
        myLabel.text = "Text on label"

If I run my application now, the label should adjust its width to fit the text. Notice, that I did not need to set width size. Adding the Top and the Leading constraints was sufficient enough.

UILabel Fit Text Size

Here is how it all looks in my Xcode project.

UILabel on Empty View

I hope this short tutorial was of some value to you. Have a look at other Swift tutorials on this blog and you might find more helpful tutorials that you will like.

1 Comment on "Make UILabel Adjust Width to Fit Text"

Leave a Reply

Your email address will not be published. Required fields are marked *