NSAttributedString '\n' ignored

winsome picture winsome · Mar 24, 2013 · Viewed 8k times · Source

I have a single view whose only UI element is a UITextView. In viewDidLoad: I create an attributed string with "Text\n" and set the text view's attributed text as such:

NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"Text\n"];  
[self.textView setAttributedText:string];

My problem is that the line break is ignored when I run the app.

If I use an NSString and setText: that doesn't happen.

NSString *string = [[NSString alloc] initWithString:@"Text\n"];  
[self.textView setText:string];

Can anyone shed some light on what is happening? I can't seem to find anything in documentation or otherwise.

Answer

Blasco73 picture Blasco73 · Jul 1, 2014

You can use this:

 NSMutableAttributedString *cr = [[NSMutableAttributedString alloc] initWithString: @"\n"];

So if you have two NSMutableAttributedString (string1 and string2) you can do:

[string1 appendAttributedString: cr];
[string1 appendAttributedString: string2];

It's horrible and not elegant.... but it works!!!