简体   繁体   English

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

[英]Setting particular font-size at the cursor point in UITextView with attributed text using Swift

I am trying to build a RichTextEditor using UITextView.我正在尝试使用 UITextView 构建 RichTextEditor。 When I apply a different font size at the end of the text, it fails to update the font size for new text typed.当我在文本末尾应用不同的字体大小时,它无法更新键入的新文本的字体大小。

I am currently having the below code which I tried to make it work:我目前有下面的代码,我试图让它工作:

Rich text outlet is富文本出口是
@IBOutlet weak var richTextView: UITextView!

The code for trying to change the font is尝试更改字体的代码是

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
    }
}

I tried adding an empty string to the end with new attributes, but that didn't work out.我尝试使用新属性在末尾添加一个空字符串,但这没有奏效。 How do I achieve setting the attribute change in the above example?在上面的例子中如何实现设置属性更改?

it fails to update the font size for new text typed.它无法更新键入的新文本的字体大小。

The way to set the attributes of the text that the user will type is to set the UITextView's typingAttributes .设置用户将要键入的文本的属性的方法是设置 UITextView 的typingAttributes

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM