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?
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"];
Change the text while keeping the attributes:
let myString = "my string" let myAttributes = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 40)] let mutableAttributedString = NSMutableAttributedString(string: myString, attributes: myAttributes) let myNewString = "my new string" mutableAttributedString.mutableString.setString(myNewString)
The results for mutableAttributedString
are
Notes
Any sub-ranges of attributes beyond index 0 are discarded. For example, if I add another attribute to the last word of the original string, it is lost after I change the string:
// additional attribute added before changing the text let myRange = NSRange(location: 3, length: 6) let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ] mutableAttributedString.addAttributes(anotherAttribute, range: myRange)
Results:
From this we can see that the new string gets whatever the attributes are at index 0 of the original string. Indeed, if we adjust the range to be
let myRange = NSRange(location: 0, length: 1)
we get
See also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With