Chirag Jain Chirag Jain - 27 days ago 10x
Objective-C Question

replace entire text string in NSAttributedString without modifying other attributes

I have a reference to

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

I guess i have to created a new
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
. How can i retain the previous attributed in the new string?


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