简体   繁体   中英

Save UITextView String With \n Instead of Line Breaks (Swift)

I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command ( \n ). How would I do this?

For example, my user inputs

Line 1
Line 2
Line 3

in the UITextView . If I was to retrieve the string...

let string = textview.text!

this would return

"Line 1
Line 2
Line 3"

when I would like for it to return

"Line1\nLine2\nLine3"

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:) ? I feel like I'm missing a fairly obvious solution...

Have you tried replacing \r with \n? or even \r\n with \n?

I hope I am not making an obvious assumption you considered, but maybe this may come in handy: Is a new line = \n OR \r\n?

Eureka! After WAY too much research and learning all about String escapes, I found a very simple solution. I'm quite surprised that this isn't an answer out there already (as far as I can tell haha) so hopefully, this helps someone!

It's actually quite simple and this will work of any String you could be using.

textView.text!.replacingOccurrences(of: "\n", with: "\\n")

Explanation : Ok so as you can tell, it's quite simple. We want to replace the newline command \n with the string "\n" . The problem is that if we replace \n with \n , it's just going to transfer over to a newline, not a string. This is why escapes are so important. As you can see, I am replacing \n with \\n . By adding an extra \ we escape the command \n entirely which turns it into a string.

I hope this helps someone! Have a great day!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM