3

I'm trying to replace some text that was selected inside a UITextView with some NSAttributedString but only the following method is available:

textView.replace(UITextRange, withText: String)

As you can see, replacing text only accepts a String and I cannot find way to replace it with an NSAttributedString.

One thing I could do is to store the whole UITextView attributedText and then perform the desired changes on a NSMutableAttributedString and then I can replace the UITextView.attributedText to be the one of the NSMutableAttributedString, but this comes with some issues for me.

If the text is already long with some NSStorage and NSAttachments this will be way more expensive.

Is there any workaround?

1 Answer 1

2

Because you can't intermix String and NSAttributedString, there's unfortunately no workaround that will let both co-exist in a text field.

But you should be able to use replaceCharacters(in:with:):

existingAttributedString.replaceCharacters(in: range, with: replacementAttributedString)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing it out! Yes I'll try the method you've suggested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.