用 NSAttributedString 替换 UITextView 选中的文本

Replace UITextView selected text with NSAttributedString

我正在尝试用 NSAttributedString 替换在 UITextView 中选择的一些文本,但只有以下方法可用:

textView.replace(UITextRange, withText: String)

如您所见,替换文本只接受 String,我找不到将其替换为 NSAttributedString 的方法。

我可以做的一件事是存储整个 UITextView attributedText,然后对 NSMutableAttributedString 执行所需的更改,然后我可以将 UITextView.attributedText 替换为其中的一个NSMutableAttributedString,但这给我带来了一些问题。

如果文本已经很长并且有一些 NSStorageNSAttachments 这会更昂贵。

有什么解决方法吗?

因为您不能混合使用 StringNSAttributedString,很遗憾,没有解决方法可以让两者在文本字段中共存。

但是你应该可以使用 replaceCharacters(in:with:):

existingAttributedString.replaceCharacters(in: range, with: replacementAttributedString)