简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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