44

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

swiftBoy
  • 34,827
  • 26
  • 133
  • 130
tika
  • 6,669
  • 2
  • 48
  • 81

3 Answers3

83

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,815
  • 2
  • 22
  • 26
rakeshbs
  • 23,816
  • 6
  • 72
  • 63
26

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
  • 552
  • 1
  • 7
  • 25
4

Note with Swift 3 you need to use updated method byWordWrapping

productNameLabel.lineBreakMode = .byWordWrapping
productNameLabel.numberOfLines = 1

enter image description here


Or for adding Ellipsis at the end use byTruncatingTail

productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1

enter image description here

swiftBoy
  • 34,827
  • 26
  • 133
  • 130
  • 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