Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line Breaks and Number of Lines in Swift Label (Programmatically)

By selecting a Label in a StoryBoard, I can select Line Break to be Word Wrap and change number of lines to be more than 1. How can I do that Programmatically in Swift?enter image description here

like image 247
tika Avatar asked Jan 04 '15 04:01

tika


People also ask

How do you add a line break in UILabel?

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

What is label in Swift?

Label is a user interface item in SwiftUI which enables you to display a combination of an image (icon, SF Symbol or other) and a text label in a single UI element.


2 Answers

You can do this to set it programmatically

 label.lineBreakMode = NSLineBreakMode.ByWordWrapping  label.numberOfLines = 3 

Swift 3/4

label.lineBreakMode = .byWordWrapping label.numberOfLines = 3 
like image 171
rakeshbs Avatar answered Sep 21 '22 04:09

rakeshbs


If you want the label to have multiple lines, do this:

var myLabel:UILabel = UILabel(frame: CGRectMake(7, 200, 370, 100)) myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping myLabel.numberOfLines = 0                      //'0' means infinite number of lines 

Do remember to increase the height in "CGRectMake(7, 200, 370, 100)"         <-- This
Otherwise the label won't be able to take the multiple lines of text.

like image 21
Zoran777 Avatar answered Sep 24 '22 04:09

Zoran777