Chirag Jain Chirag Jain - 1 year ago 159
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?

Answer Source

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"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download