UILabel - Wordwrap text

IosIphoneCocoa TouchUilabelWord Wrap

Ios Problem Overview


Is there any way to have a label wordwrap text as needed? I have the line breaks set to word wrap and the label is tall enough for two lines, but it appears that it will only wrap on line breaks. Do I have to add line breaks to make it wrap properly? I just want it to wrap if it can't fit it in horizontally.

Ios Solutions


Solution 1 - Ios

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

Solution 2 - Ios

UILabel has a property lineBreakMode that you can set as per your requirement.

Solution 3 - Ios

In Swift you would do it like this:

    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.numberOfLines = 0

(Note that the way the lineBreakMode constant works is different to in ObjC)

Solution 4 - Ios

Xcode 10, Swift 4

Wrapping the Text for a label can also be done on Storyboard by selecting the Label, and using Attributes Inspector.

Lines = 0 Linebreak = Word Wrap

enter image description here

Solution 5 - Ios

Xcode 12.5.1, Swift 5.

I found that even though I had Lines = 0 and LineBreak = Word Wrap set, it still didn't wrap the long label text. Double check your label constraints in IB (or wherever you set them).

I found that sometimes IB tries to fix the constraint settings and adds a >= or <= constraint for leading and trailing edges.

This label constraint will not wrap the text:

enter image description here


But this will:

enter image description here

Notice the >= on the Label.trailing edge in the first picture. Set this to = and the text should wrap.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodezyView Question on Stackoverflow
Solution 1 - IosKendall Helmstetter GelnerView Answer on Stackoverflow
Solution 2 - IosGregView Answer on Stackoverflow
Solution 3 - IosNathanView Answer on Stackoverflow
Solution 4 - IosNaishtaView Answer on Stackoverflow
Solution 5 - IosMichaelView Answer on Stackoverflow