代码之家  ›  专栏  ›  技术社区  ›  Crashalot

iOS:是否在UITextView的光标处插入属性字符串?

  •  0
  • Crashalot  · 技术社区  · 7 年前

    UITextView 用于在光标处使用 insertText 作用有没有一种干净的方法来处理属性文本?

    这是唯一的方法来分割 attributedText 属性分为两部分—游标前和游标后—然后将新的属性字符串附加到游标前属性文本,然后再附加游标后属性文本?

    2 回复  |  直到 7 年前
        2
  •  0
  •   Crashalot    7 年前

    根据@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
    }