Reputation: 3969
I want to add a line feed on an UILabel
. On storyboard using \n
does not work at all.
Here is an example.
On StoryBoard I've created 2 UILabel
and set their content in dedicated field:
Label 1\nhello
with \n
created by ALT+RETURNLabel 2\nhello
with explicit \n
Then I added a third label and configure it on controller, not on Story Board:
label3.numberOfLines = 0 label3.text = "Label3\nhello"
This is a brand new project, on Xcode 8. Language is Swift 3.1 and AutoLayout is off. So there must not have any interferences from any external libraries, nor AutoLayout.
Here is the rendering.
UILabel
behavior is not the same if used on StoryBoard or code source and this is really disturbing. Of course while you faced and solved this problem everything seems to be cristal clear, as the answer is known.
This problem is easily solved by using a UITextView
instead of UILabel
. So as for now and until I rather prefer using UITextView
for displaying simple text on multilines despite the fact UILabel
must work for this purpose.
Upvotes: 1
Views: 3179
Reputation: 39
Press Ctrl + Enter (between two words)
Simply Add "\n"
Upvotes: 0
Reputation: 1001
In UILabels you simply can't use
\n
You have to use
Option + Enter
to go to the next line.
Upvotes: 1
Reputation: 4711
There is a difference between the carriage return character (\n) and the characters \n. The singular character \n is a carriage return and as you have seen splits the line. However the two characters \ & n just represent the two different characters themselves.
When doing a Storyboard in Interface Builder and characters you enter into a UILabel are all counted as individual characters so if you type \n you are actually entering the character '\' and the character 'n'. To enter the special single carriage return character (\n) you therefore have to use ALT+RETURN.
Now in code you can be more flexible. When entering some text like this "Line1\nLine2" the \n is treated as the single carriage return character so to enter the characters '\' & 'n' next to each other you have to use "Line1\nLine2" (the double \ indicates a single '\' character).
So when it works you are getting the single carriage return character (\n) in the string and when it doesn't you are getting the two separate characters.
You don't mention how the \n is added when it doesn't work (outside of a Storyboard) but it must be being added to the string as two separate characters.
As an example:
let str1 = "12345\n67890
let str2 = "12345\\n67890
print (str1.characters.count) // prints 11
print (str2.characters.count) // prints 12
Upvotes: 2
Reputation: 614
In UILabels you simply can't use
\n
You have to use
Alt + Enter
to move to the next line.
Upvotes: 9