2

How can a NSAttributedString formatted string be appended to an existing textView.attributedText formatted string from UITextView?

From this answer, I can see that a conversion from and to NSMutableAttributedString / NSAttributedString can be done with appendAttributedString() / append() but this does not work when I'm pulling and updating a textView.attributedText like this:

let string2 = NSAttributedString(string: "success", attributes: [NSAttributedStringKey.foregroundColor: UIColor.green])

let newMutableString = textView.attributedText.copy() as! NSMutableAttributedString
newMutableString.append(string2)

textView.attributedText = newMutableString.copy() as! NSAttributedString

Error message:

Could not cast value of type 'NSConcreteAttributedString' (0x10c7dff30) to 'NSMutableAttributedString' (0x10c7dff80).
powtac
  • 40,542
  • 28
  • 115
  • 170

1 Answers1

3

I believe you need to copy it with mutableCopy because you want to get a mutable copy from an immutable one:

let newMutableString = textView.attributedText.mutableCopy() as! NSMutableAttributedString
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
TNguyen
  • 1,041
  • 9
  • 24