Swift — Dynamic UILabel Text

While working on a project making multiple API calls and parsing text from the API response I ran into a problem with the unpredictable amount of text i was receiving. Some of the text easily fit in 2–3 lines and other text required 6–7 lines or more to properly fit. I kept adjusting my text labels using Line Breaks (word wrap) and changing the Line Count to account for the lines of text I received back from the API. I quickly got the awful feeling that is not very smart, there’s got to be a better way. And of course there is, as always, your code should be dynamic, it should be able to adjust to the incoming data. The same rule applies here, my text label should be adaptive to a single or multiline.

The Solution: lets set up a simple project for practice. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

Set the Label properties as below image:

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

Now set the priority of the trailing constraint of UILabel as 749

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]


@IBAction func updateLabelText(sender: UIButton) {
if count > 3 {
count = 0
}
textLabel.text = items[count]
count = count + 1
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.textLabel.sizeToFit()
//self.textLabel.preferredMaxLayoutWidth = 500
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


}

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.

Show your support

Clapping shows how much you appreciated Dennis Vera’s story.