Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace entire text string in NSAttributedString without modifying other attributes

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?

like image 470
Chirag Jain Avatar asked May 15 '15 19:05

Chirag Jain


2 Answers

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"]; 
like image 58
Artal Avatar answered Sep 18 '22 17:09

Artal


Swift

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

  • enter image description here
  • enter image description here

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:

  • enter image description here
  • enter image description here

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

  • enter image description here
  • enter image description here

See also

  • my main answer about Swift attributed strings
like image 24
Suragch Avatar answered Sep 17 '22 17:09

Suragch