powtac
powtac

Reputation: 41050

Append formatted string to already formatted string from UITextView?

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).

Upvotes: 2

Views: 334

Answers (1)

TNguyen
TNguyen

Reputation: 1051

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

Upvotes: 3

Related Questions