NSAttributedString '\n' ignored

白昼怎懂夜的黑 提交于 2019-12-22 03:21:54

问题


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.


回答1:


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!!!




回答2:


I would advise you to use:

[[NSAttributedString alloc] initWithHTML:[@"Text<BR />" dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:NULL];

I use this all the time and it works perfectly. I even made a macro out of it:

#define html2AttributedString(htmlString)                                                                   \
    [[[NSAttributedString alloc] initWithHTML:[(htmlString) dataUsingEncoding:NSUTF8StringEncoding]         \
    documentAttributes:NULL] autorelease]

And then, you can make macro for color, alignment, font, etc…

In short, you just need to replace all the "\n" in your string with <BR /> and use the code provided above. For the replacement part, use:

[yourString stringByReplacingOccurrencesOfString:... withString:…];

For iOS, you can check out this page in which they give you a replacement.

Our initWithHTML methods aim to perfectly match the output from the Mac version. This is possible to achieve for characters and I have unit tests in place that make certain this keeps being perfect. Regarding the attributes there are many things that have to be done slightly different on iOS to achieve the same look. I won’t bother you with the details there.



来源:https://stackoverflow.com/questions/15594467/nsattributedstring-n-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!