替换NSAttributedString中的整个文本字符串而不修改其他属性 [英] replace entire text string in NSAttributedString without modifying other attributes
问题描述
我引用了 NSAttributedString
,我想更改属性字符串的文本。
I have a reference to NSAttributedString
and i want to change the text of the attributed string.
I我必须创建一个新的 NSAttributedString
并使用这个新字符串更新引用。但是,当我这样做时,我失去了之前字符串的归属。
I guess i have to created a new NSAttributedString
and update the reference with this new string. However when i do this i lose the attributed of previous string.
NSAttributedString *newString = [[NSAttributedString alloc] initWithString:text];
[self setAttributedText:newString];
我在中引用了旧的属性字符串self.attributedText
。如何保留新字符串中的先前属性?
I have reference to old attributed string in self.attributedText
. How can i retain the previous attributed in the new string?
推荐答案
您可以使用NSMutableAttributedString并只更新字符串,获取属性不要改变。
示例:
You can use NSMutableAttributedString and just update the string, the attributes won't change. Example:
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:@"my string" attributes:@{NSForegroundColorAttributeName: [UIColor blueColor], NSFontAttributeName: [UIFont systemFontOfSize:20]}];
//update the string
[mutableAttributedString.mutableString setString:@"my new string"];
这篇关于替换NSAttributedString中的整个文本字符串而不修改其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!