iOS: 在光标处为 UITextView 插入属性字符串?

iOS: insert attributed string at cursor for UITextView?

UITextView 允许您使用 insertText 函数在光标处插入纯文本。有没有一种干净的方法来处理属性文本?

是将 attributedText 属性 分成两部分的唯一方法——前游标和 post-游标——然后将新的属性字符串附加到前游标光标属性文本,然后附加 post-光标属性文本?

通过调用 https://developer.apple.com/documentation/foundation/nsmutableattributedstring/1414947-insert 插入文本视图属性文本的可变副本。

根据@matt 的建议,这里有一个 Swift 4.x 函数:

fileprivate func insertAtTextViewCursor(attributedString: NSAttributedString) {
    // Exit if no selected text range
    guard let selectedRange = textView.selectedTextRange else {
        return
    }

    // If here, insert <attributedString> at cursor
    let cursorIndex = textView.offset(from: textView.beginningOfDocument, to: selectedRange.start)
    let mutableAttributedText = NSMutableAttributedString(attributedString: textView.attributedText)
    mutableAttributedText.insert(attributedString, at: cursorIndex)
    textView.attributedText = mutableAttributedText
}