首页 > 解决方案 > 在 UITextView.attributedText 中插入 unicode 的正确方法

问题描述

我想在 UITextView 中混合 2 种字体。Font1 有特殊的 unicode 字符,font2 没有。如果 UITextView 的主字体是 font2,如何将 Font1 插入 UITextView 而不光标跳到末尾?因为 .attributedText 是不可变的。我假设我需要创建一个 NSMutableString 并将其分配给 .attributedText。但是,这会将光标置于末尾。有没有办法在光标选择处插入 Font 1 而不会让光标跳到末尾?提前感谢您的帮助。

标签: iosuitextviewnsattributedstring

解决方案


您可以使用以下功能将属性插入光标点。

https://developer.apple.com/documentation/foundation/nsmutableattributedstring/1414947-insert

func insertAtTextViewCursor(attributedString: NSAttributedString) {

    // Find out the cursor point
    guard let selectedRange = textView.selectedTextRange else { return }

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

推荐阅读