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?
Asked
Active
Viewed 1e+01k times
45
-
It is recommended to go with design-time setting since at times the run-time may not work as in my case. – Jayprakash Dubey Aug 01 '16 at 05:05
3 Answers
87
You can do this to set it programmatically
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 3
Swift 3/4
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 3

Gabriel Lidenor
- 2,905
- 2
- 25
- 26

rakeshbs
- 24,392
- 7
- 73
- 63
-
2Not much reason to set the number of lines to 1 if you want to wrap text. – rmaddy Jan 04 '15 at 04:33
-
2
-
1
-
http://stackoverflow.com/questions/15161348/how-can-i-compute-the-number-of-lines-of-a-uilabel-with-a-fixed-width – rakeshbs Feb 16 '16 at 12:54
-
@rakeshbs plz look here for my question https://stackoverflow.com/questions/46723070/label-disappear-when-changing-font-size-to-25-in-swift – dinesh sharma Oct 14 '17 at 11:11
-
For resizing dynamically, refer to this answer https://stackoverflow.com/a/31179855/2625761 – Zoran777 May 28 '18 at 11:58
27
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.

Zoran777
- 564
- 2
- 7
- 25
-
1Although I marked above as right answer because that is what I needed. This is `recommended` for auto layouts and dynamic height. – tika Sep 09 '16 at 16:00
-
Agreed! And as much as possible, dynamic needs should be incorporated always! – Zoran777 Sep 19 '16 at 08:14
-
4
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

swiftBoy
- 35,607
- 26
- 136
- 135
-
plz look here for my question https://stackoverflow.com/questions/46723070/label-disappear-when-changing-font-size-to-25-in-swift – dinesh sharma Oct 14 '17 at 11:11