Swift Multi Line Label and More
We learn how to make a multi line label in Swift, and other methods for fitting text into a label in Swift. First of all create a new single view application in XCode and add 4 labels to your storyboard as follows:
Multi Line Label
Set the text on the labels to “Hello this is Andrew” or anything else, so long as it can’t fit the label!
Now select the second label from the top. Then go to the attributes inspector and set the lines to 0.
Now if you resize the label to be taller, you will notice the text now goes across several lines. Setting the lines to 0 tells the label to take up as much lines as it can. Otherwise if its 1, 2, 3, etc.. it will only take up that many lines. By default labels take up 1 line.
You can also do this in code with:
label.numberOfLines = 0
Other ways to fit text on labels
Lets look at some other ways we can fit text on labels. Connect up our labels on the storyboard all as outlets in our code names as follows:
@IBOutlet var greet1: UILabel! @IBOutlet var greet2: UILabel! @IBOutlet var greet3: UILabel! @IBOutlet var greet4: UILabel!
The first way is by truncating text, this means that some text is cut off. We can adjust the cut off point to be at the start of the label, middle or end. Add this in viewDidLoad().
greet1.lineBreakMode = .byTruncatingMiddle
The above line of code will cut the text in the middle and show the start and ending of a label. So worst case if you can’t fit everything on a label you can adjust it’s cutoff point.
Next up we can adjust the text size to fit the label the best it can, to do this on greet3, simply add the following line of code also in viewDidLoad()
greet3.adjustsFontSizeToFitWidth = true
Optimal height for a label
What if we want to adjust a label’s height to be optimal for it’s contents? Or calculate the height of label if we were to size it to fit all it’s contents?
To do this simply create a new empty Swift file named UILabel.swift and code it as follows:
import UIKit extension UILabel { var optimalHeight : CGFloat { get { let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.font = self.font label.text = self.text label.sizeToFit() return label.frame.height } } }
The variable optimalHeight will return the optimal height for a given label. To use this on our greet4 label in ViewController.Swift add the following in viewDidLoad():
var greet4Height = greet4.optimalHeight greet4.frame = CGRect(x: greet4.frame.origin.x, y: greet4.frame.origin.y, width: greet4.frame.width, height: greet4Height) greet4.backgroundColor = UIColor.yellow
We set the background color to yellow to show how it sets to the optimal height. For a more detailed explanation see the youtube video here.