Search code examples
swiftuitextviewnsattributedstringrich-text-editornsmutableattributedstring

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


I am trying to build a RichTextEditor using UITextView. 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?


Solution

  • 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.

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