I'm working on a document-based SwiftUI app for Mac and iOS that uses SwiftUI's TextEditor
for entering text. I want to insert markup, such as Markdown formatting, into the text editor. For example in Markdown to create bold text, I would select the text, press Cmd-B (or use a button or menu), and insert the asterisks at the start and the end of the selection.
With NSTextView
and UITextView
I can access the range of the selection using the selectedRange
property. But looking through the documentation for TextEditor
, I see no way of getting the range of the selection. Without the selection range there's no way for me to insert the markup in the correct position.
How do I get the range of the selection in a SwiftUI text editor?