NSAttributedString'\ n'被忽略

时间:2013-03-24 02:22:25

标签: ios ios6 uitextview nsattributedstring end-of-line

我有一个视图,其唯一的UI元素是UITextView。在viewDidLoad:中,我使用“Text \ n”创建属性字符串,并将文本视图的属性文本设置为:

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

我的问题是,当我运行应用程序时,会忽略换行符。

如果我使用不会发生的NSStringsetText:

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

任何人都可以了解正在发生的事情吗?我似乎无法在文档或其他方面找到任何内容。

2 个答案:

答案 0 :(得分:6)

您可以使用:

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

因此,如果你有两个NSMutableAttributedString(string1和string2),你可以这样做:

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

它太可怕而且不优雅......但它确实有效!!!

答案 1 :(得分:2)

我建议你使用:

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

我一直使用它,它完美无缺。我甚至用它制作了一个宏:

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

然后,您可以为颜色,对齐,字体等制作宏...

简而言之,您只需要用"\n"替换字符串中的所有<BR />并使用上面提供的代码。对于更换部件,请使用:

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

对于iOS,您可以查看他们为您提供替换的this page

  

我们的initWithHTML方法旨在完美匹配来自的输出   Mac版。这可以实现我和我的角色   单元测试,确保这一点保持完美。   关于属性,有许多事情需要完成   在iOS上略有不同,实现相同的外观。我不会打扰你   有详细信息。