使用Swift使用属性文本在UITextView的光标处设置特定的字体大小

时间:2019-12-02 23:36:30

标签: swift uitextview nsattributedstring rich-text-editor nsmutableattributedstring

我正在尝试使用UITextView构建RichTextEditor。 当我在文本末尾应用不同的字体大小时,它无法为输入的新文本更新字体大小。

我目前正在尝试执行以下代码:

富文本格式的出口是
@IBOutlet weak var richTextView: UITextView!

尝试更改字体的代码是

func setAttributesForSelectedTextRange(_ attributes: [NSAttributedString.Key: Any]) {
    if let text = richTextView.attributedText.mutableCopy() as? NSMutableAttributedString, let selectedRange = richTextView.selectedTextRange {
        let cursorPosition = richTextView.offset(from: richTextView.beginningOfDocument, to: selectedRange.start)
        text.addAttributes(attributes, range: richTextView.selectedRange)
        if selectedRange.end == richTextView.endOfDocument {
            text.append(NSAttributedString(string: "", attributes: attributes))
        }

        richTextView.attributedText = text
    }
}

我尝试在具有新属性的末尾添加一个空字符串,但是没有成功。 在上面的示例中,如何实现设置属性更改?

1 个答案:

答案 0 :(得分:1)

  

它无法更新键入的新文本的字体大小。

设置用户将键入的文本属性的方法是设置UITextView的typingAttributes

https://developer.apple.com/documentation/uikit/uitextview/1618629-typingattributes