Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a new line in swift

Tags:

string

swift

Is there a way to have a way to make a new line in swift like "\n" for java?

var example: String = "Hello World \n This is a new line" 
like image 526
Westink Avatar asked Feb 14 '16 01:02

Westink


People also ask

How do I add a new line?

To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.

How do I start a new line in Xcode?

Search for "line" under the Text tab. There are lots of "Insert Newline" commands for which you can set key combos. There's Ctrl+o, Cmd+Enter, Opt+Enter, etc.

How do you string a new line?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is the code for new line?

LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.


2 Answers

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.

like image 72
BradzTech Avatar answered Sep 30 '22 09:09

BradzTech


Also useful:

let multiLineString = """                   Line One                   Line Two                   Line Three                   """ 
  • Makes the code read more understandable
  • Allows copy pasting
like image 29
Pbk Avatar answered Sep 30 '22 10:09

Pbk