UILabel - Wordwrap text

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.

Answers


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.


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


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)


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


Need Your Help

Diff syntax highlighting in Github Markdown

github markdown syntax-highlighting

I'm writing documents that should explain code in C# using Markdown.

Convert a String to an array of characters swift 2.0

arrays string swift character swift2

I need to convert a string into an array of characters. This work in Swift 1.2 and lower but doesn't since Swift 2.0