I want to replace a substring (e.g. @"replace"
) of an NSAttributedString
with another NSAttributedString
.
I am looking for an equivalent method to NSString
's stringByReplacingOccurrencesOfString:withString:
for NSAttributedString
.
Convert your attributed string into an instance of NSMutableAttributedString
.
The mutable attributed string has a mutableString
property. According to the documentation:
"The receiver tracks changes to this string and keeps its attribute mappings up to date."
So you can use the resulting mutable string to execute the replacement with replaceOccurrencesOfString:withString:options:range:
.
Here is how you can change the string of NSMutableAttributedString, while preserving its attributes:
Swift:
// first we create a mutable copy of attributed text
let originalAttributedText = nameLabel.attributedText?.mutableCopy() as! NSMutableAttributedString
// then we replace text so easily
let newAttributedText = originalAttributedText.mutableString.setString("new text to replace")
Objective-C:
NSMutableAttributedString *newAttrStr = [attribtedTxt.mutableString setString:@"new string"];
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