How do I make a new line in swift
You can use the following code;
var example: String = "Hello World \r\n This is a new line"
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1 Phone Number: output of string2
You should be able to use \n
inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n
for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
- If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
- In some networking use cases, use
\r\n
instead, which is the Windows newline.
Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
Also useful:
let multiLineString = """
Line One
Line Two
Line Three
"""
- Makes the code read more understandable
- Allows copy pasting