NSAttributedString’\ n’被忽略

我有一个视图,其唯一的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]; 

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

你可以用这个:

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

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

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

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

我建议你使用:

 [[NSAttributedString alloc] initWithHTML:[@"Text
" dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:NULL];

我一直使用它,它完美地运作。 我甚至做了一个宏:

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

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

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

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

对于iOS,您可以查看他们为您提供替代品的页面。

我们的initWithHTML方法旨在完美匹配Mac版本的输出。 这可以实现角色,我有适当的unit testing,以确保这是完美的。 关于属性,在iOS上有许多必须略微不同的东西才能实现相同的外观。 我不会打扰你那里的细节。