具有 n 或换行符的 NSString

有人知道如何在 NSString 中使用换行符吗

[NSString stringWithFormat:@"%@,\n%@", mystring1,mystring2];
131052 次浏览

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0

myView.numberOfLines=0;

\n\r seems working for me.

I am using Xcode 4.6 with IOS 6.0 as target. Tested on iPhone 4S. Try it by yourself.

Feng Chiu

NSString *str1 = @"Share Role Play Photo via Facebook, or Twitter for free coins per photo.";
NSString *str2 = @"Like Role Play on facebook for 50 free coins.";
NSString *str3 = @"Check out 'What's Hot' on other ways to receive free coins";




NSString *msg = [NSString stringWithFormat:@"%@\n%@\n%@", str1, str2, str3];

try this

 [NSString stringWithFormat:@"%@\n%@",string1,string2];

I found that when I was reading strings in from a .plist file, occurrences of "\n" were parsed as "\\n". The solution for me was to replace occurrences of "\\n" with "\n". For example, given an instance of NSString named myString read in from my .plist file, I had to call...

myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

... before assigning it to my UILabel instance...

myLabel.text = myString;

Line breaks character for NSString is \r

correct way to use [NSString stringWithFormat:@"%@\r%@",string1,string2];

\r ----> carriage return

\n is the preferred way to break a line. \r will work too. \n\r or \r\n are overkill and may cause you issues later. Cocoa, has specific paragraph and line break characters for specific uses NSParagraphSeparatorCharacter, NSLineSeparatorCharacter. Here is my source for all the above.

In Swift 3, its much simpler

let stringA = "Terms and Conditions"
let stringB = "Please read the instructions"


yourlabel.text =  "\(stringA)\n\(stringB)"

or if you are using a textView

yourtextView.text =  "\(stringA)\n\(stringB)"

In case \n or \r is not working and if you are working with uiwebview and trying to load html using < br > tag to insert new line. Don't just use < br > tag in NSString stringWithFormat.

Instead use the same by appending. i.e by using stringByAppendingString

 yourNSString = [yourNSString stringByAppendingString:@"<br>"];