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

iOSiPhone/iPadMobile Development

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 \n 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 \n to add to the label to check \n the number of lines work or not."
}

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

raja
Published on 18-Jan-2019 15:07:51
Advertisements