【问题标题】:Correct way to insert unicode in UITextView.attributedText在 UITextView.attributedText 中插入 unicode 的正确方法
【发布时间】:2019-02-11 17:59:33
【问题描述】:

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

【问题讨论】:

    标签: ios uitextview nsattributedstring


    【解决方案1】:

    您可以使用以下函数将属性插入光标点。

    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
    }
    

    【讨论】:

    • 好的,谢谢!!但是最后一条语句会使光标跳转到文档的末尾。我无法将文本滚动回确切的上一个光标点。您会认为保存 contentOffset 和恢复会起作用,但事实并非如此。 caretRectForPosition 有效,但并没有真正将其放回原处。
    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2011-07-03
    相关资源
    最近更新 更多