replace entire text string in NSAttributedString without modifying other attributes

Chirag Jain picture Chirag Jain · May 15, 2015 · Viewed 30.6k times · Source

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

Artal picture Artal · May 15, 2015

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