Chirag Jain Chirag Jain - 2 months ago 25
Objective-C Question

replace entire text string in NSAttributedString without modifying other attributes

I have a reference to

NSAttributedString
and i want to change the text of the attributed string.

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];


I have reference to old attributed string in
self.attributedText
. How can i retain the previous attributed in the new string?

Answer

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"];