【问题标题】:iOS: insert attributed string at cursor for UITextView?iOS:在 UITextView 的光标处插入属性字符串?
【发布时间】:2018-12-11 17:01:59
【问题描述】:

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

是将attributedText 属性拆分为两部分(前光标和后光标)的唯一方法,然后将新的属性字符串附加到前光标属性文本,然后附加后光标属性文字?

【问题讨论】:

  • 我猜:从myTextView.attributedText 创建一个名为tempAttributedStringNSMutableAttributedString。从selectedRange 获取范围。使用 replaceCharacters(in:with:) 在该范围内插入。如果范围长度为 0,那么它是一个“插入”,否则它是一个替换(即使在这两种情况下都是替换)。将该 tempAttributedStringText 设置为 myTextView.AttributedText。重新定位selectedRange

标签: ios uitextview nsattributedstring


【解决方案1】:

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

【讨论】:

  • 非常感谢!发布了一个受您的回复启发的答案,但显然给了您信誉。
【解决方案2】:

按照@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
}

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2015-10-18
    • 2016-07-04
    相关资源
    最近更新 更多