Line Breaks and Number of Lines in Swift Label (Programmatically)
92,955
Solution 1
You can do this to set it programmatically
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 3
Swift 3/4
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 3
Solution 2
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.
Solution 3
Note with Swift 3 you need to use updated method byWordWrapping
productNameLabel.lineBreakMode = .byWordWrapping
productNameLabel.numberOfLines = 1
Or for adding Ellipsis at the end use byTruncatingTail
productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1
Related videos on Youtube
Author by
tika
Chronic Workaholic! Worked on PHP, C#/ASP.NET, Java, MsSql/Mysql, Swift, and Jquery. LinkedIn: https://www.linkedin.com/in/pahadi Website: https://tika.me
Updated on July 09, 2022Comments
-
tika almost 2 years
By selecting a Label in a StoryBoard, I can select
Line Break
to beWord Wrap
and change number of lines to be more than 1. How can I do that Programmatically in Swift?-
Jayprakash Dubey almost 8 yearsIt is recommended to go with design-time setting since at times the run-time may not work as in my case.
-
-
rmaddy over 9 yearsNot much reason to set the number of lines to 1 if you want to wrap text.
-
rakeshbs over 9 yearsI was just demonstrating how to change it.
-
Admin about 8 yearsHow to do this dynamically according to text length?
-
rakeshbs about 8 years
-
tika over 7 yearsAlthough I marked above as right answer because that is what I needed. This is
recommended
for auto layouts and dynamic height. -
Zoran777 over 7 yearsAgreed! And as much as possible, dynamic needs should be incorporated always!
-
JCarlosR about 7 yearsIs it necessary to create the label always programatically?
-
dinesh sharma over 6 years@rakeshbs plz look here for my question stackoverflow.com/questions/46723070/…
-
dinesh sharma over 6 yearsplz look here for my question stackoverflow.com/questions/46723070/…
-
Zoran777 almost 6 yearsFor resizing dynamically, refer to this answer stackoverflow.com/a/31179855/2625761