ech*_*cho 8 objective-c nsattributedstring
例如,我有3个句子,比如@"很久很久以前.",@"有一个孩子.",@"bla bla bla"我在下面做了一个方法
- (void)appendText:(NSString*)text
{
NSMutableAttributedString *originalText = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
NSAttributedString *appendText = [[NSAttributedString alloc] initWithString:text
attributes:@{NSForegroundColorAttributeName:DefaultTextColor}];
[originalText appendAttributedString:appendText];
_textView.attributedText = originalText;
}
Run Code Online (Sandbox Code Playgroud)
所以我调用了appendText 3次
[self appendText:@"Long long ago."];
[self appendText:@"There is a child."];
[self appendText:@"bla bla bla."];
Run Code Online (Sandbox Code Playgroud)
我预期的结果是
Long long ago.There is a child.bla bla bla.
Run Code Online (Sandbox Code Playgroud)
但输出是
Long long ago.
There is a child.
bla bla bla
Run Code Online (Sandbox Code Playgroud)
为什么appendAttributedString在新行中显示附加的字符串?如何将附加文本放在一个段落中?
谢谢你的帮助.
rma*_*ddy 12
根据我自己的经验,当你设置attributedText属性时UITextView,文本会添加一个换行符.因此,当您稍后attributedText从中检索时UITextView,此换行符位于文本的末尾.因此,当您添加更多文本时,换行符位于中间(另一个添加到结尾).
我不知道这是不是UITextView或可能是一个错误NSAttributedString.
一种解决方法是更新代码,如下所示:
- (void)appendText:(NSString*)text {
NSMutableAttributedString *originalText = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
// Remove any trailing newline
if (originalText.length) {
NSAttributedString *last = [originalText attributedSubstringFromRange:NSMakeRange(originalText.length - 1, 1)];
if ([[last string] isEqualToString:@"\n"]) {
originalText = [originalText attributedSubstringFromRange:NSMakeRange(0, originalText.length - 1)];
}
}
NSAttributedString *appendText = [[NSAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:DefaultTextColor}];
[originalText appendAttributedString:appendText];
_textView.attributedText = originalText;
}
Run Code Online (Sandbox Code Playgroud)