附加 NSSting 后保留 textView 文本的颜色
Keep the colors of the textView text after appending NSSting
我正在使用下一个方法来更改 textView 中几个单词的颜色:
+(void)changeColorToTextObject : (UITextView *)textView ToColor : (UIColor *)color FromLocation : (int)location length : (int)length
{
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: textView.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
[textView setAttributedText: text];
}
它看起来像这样:
但是当我向该文本添加新值时,颜色消失了。
myTextView.text = [myTextView.text stringByAppendingString:newStr];
看起来像这样:
如何使用新字符串保持颜色像以前一样?
而不是 myTextView.text = [myTextView.text stringByAppendingString:newStr];
使用:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:myTextView.attributedText];
NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:newStr];
[text appendAttributedString:newAttrString];
myTextView.attributedText = text;
您的代码不起作用,因为您正在将新字符串分配给 myTextView
的 text
属性。 text
只是一个 NSString
属性,因此无法显示颜色或其他可以使用 NSAttributedString
.
显示的内容
注意写myTextView.attributedText = text;
会调用属性setterattributedText
,因此 100% 等同于 [myTextView setAttributedText:text];
,只是符号不同。
我正在使用下一个方法来更改 textView 中几个单词的颜色:
+(void)changeColorToTextObject : (UITextView *)textView ToColor : (UIColor *)color FromLocation : (int)location length : (int)length
{
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: textView.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(location, length)];
[textView setAttributedText: text];
}
它看起来像这样:
但是当我向该文本添加新值时,颜色消失了。
myTextView.text = [myTextView.text stringByAppendingString:newStr];
看起来像这样:
如何使用新字符串保持颜色像以前一样?
而不是 myTextView.text = [myTextView.text stringByAppendingString:newStr];
使用:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:myTextView.attributedText];
NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:newStr];
[text appendAttributedString:newAttrString];
myTextView.attributedText = text;
您的代码不起作用,因为您正在将新字符串分配给 myTextView
的 text
属性。 text
只是一个 NSString
属性,因此无法显示颜色或其他可以使用 NSAttributedString
.
注意写myTextView.attributedText = text;
会调用属性setterattributedText
,因此 100% 等同于 [myTextView setAttributedText:text];
,只是符号不同。