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

enter image description here


Or for adding Ellipsis at the end use byTruncatingTail

productNameLabel.lineBreakMode = .byTruncatingTail
productNameLabel.numberOfLines = 1

enter image description here

Share:
92,955

Related videos on Youtube

tika
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, 2022

Comments

  • tika
    tika almost 2 years

    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

    • Jayprakash Dubey
      Jayprakash Dubey almost 8 years
      It is recommended to go with design-time setting since at times the run-time may not work as in my case.
  • rmaddy
    rmaddy over 9 years
    Not much reason to set the number of lines to 1 if you want to wrap text.
  • rakeshbs
    rakeshbs over 9 years
    I was just demonstrating how to change it.
  • Admin
    Admin about 8 years
    How to do this dynamically according to text length?
  • rakeshbs
    rakeshbs about 8 years
  • tika
    tika over 7 years
    Although I marked above as right answer because that is what I needed. This is recommended for auto layouts and dynamic height.
  • Zoran777
    Zoran777 over 7 years
    Agreed! And as much as possible, dynamic needs should be incorporated always!
  • JCarlosR
    JCarlosR about 7 years
    Is it necessary to create the label always programatically?
  • dinesh sharma
    dinesh sharma over 6 years
    @rakeshbs plz look here for my question stackoverflow.com/questions/46723070/…
  • dinesh sharma
    dinesh sharma over 6 years
    plz look here for my question stackoverflow.com/questions/46723070/…
  • Zoran777
    Zoran777 almost 6 years
    For resizing dynamically, refer to this answer stackoverflow.com/a/31179855/2625761