Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString with \n or line break

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

[NSString stringWithFormat:@"%@,\n%@", mystring1,mystring2];
like image 683
Dave Avatar asked Mar 17 '10 01:03

Dave


4 Answers

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

like image 115
Anthony F Avatar answered Oct 20 '22 07:10

Anthony F


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;
like image 45
Andy A Avatar answered Oct 20 '22 07:10

Andy A


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;
like image 26
Adil Hussain Avatar answered Oct 20 '22 06:10

Adil Hussain


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];
like image 12
Mohit Avatar answered Oct 20 '22 07:10

Mohit