NSString with \n or line break

2019-01-13 00:38发布

Does anyone know how to use line breaks in NSString? I need to do something like this -

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

10条回答
Ridiculous、
2楼-- · 2019-01-13 00:45

try this ( stringWithFormat has to start with lowercase)

 [NSString stringWithFormat:@"%@\n%@",string1,string2];
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-13 00:48

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>"];
查看更多
疯言疯语
4楼-- · 2019-01-13 00:50

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)"
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-13 00:51

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];

查看更多
姐就是有狂的资本
6楼-- · 2019-01-13 00:51
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];
查看更多
beautiful°
7楼-- · 2019-01-13 00:52

\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.

查看更多
登录 后发表回答