Getting SwiftUI TextEditor's Selection Range

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 NSTextViewand 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?

Replies

Hi @szymczyk, did you find a solution to your question? If so could you please share the answer?

  • No, I did not find a solution.

Add a Comment

It's still using NSTextView inside. Here's a solution:

import SwiftUI

struct MyView: View {
    @State var myString = "Hello world"

    var body: some View {

        TextEditor(text: $myString)
            .onReceive(NotificationCenter.default.publisher(for: NSTextView.didChangeSelectionNotification), perform: { notification in
                if let textView = notification.object as? NSTextView {
                    print(textView.selectedRange())
                }
            })

    }
}