How to add line break for UILabel in iOS/iPhone?


Line break in a UILabel is used to change how the text appears on a label. Suppose a label has text more than two lines but by default the Line break in a UILabel is used to change how the text appears on a label. Suppose a label has text more than two lines but by default the label shows 1 line and wraps/ trims the text that’s more than the label size.

This can be done in multiple ways. Three of them are mentioned below.

On the storyboard add a label.

Give top constraint, trailing and leading constraint.

Method One − Editing with the Storyboard.

Select the label you want to edit, go to it’s attribute inspector and from the lines option make it 0 which should be 1 by default. If you do this the number of lines will become 0 which means that it’s infinite now.

Method Two − Programmatically changing the number of lines

Create the outlet of the label we just created.

In the viewDidLoad Method of your controller, add the following code.

override func viewDidLoad() {
super.viewDidLoad()
self.lbl.numberOfLines = 0
}

Method Three − Programmatically adding line breaks in the text

To add line breaks in the text we’ll use
character in the string we want to assign to the label.

Add the following code to the viewDidLoad Method of your controller class.

override func viewDidLoad() {
super.viewDidLoad()
self.lbl.numberOfLines = 0
self.lbl.text = "whatever text you want 
to add to the label to check
the number of lines work or not." }

When we run the above code below is the result produced.

Updated on: 29-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements