1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That worked like a charm. I didn't know about that parameter's existence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.