SwiftUI TextEditor: replaced text jumps outside current selection

I have a text editor where I replace the selected text when a button is tapped. Most of the time it works, but sometimes the new text is inserted at the end of the text instead of at the selected position. Is this a bug?

@Bindable var note: Richnote
@State private var selection = AttributedTextSelection()

var body: some View {
        VStack {
            TextEditor(text: $note.content, selection: $selection)
Button("Replace text") {
                let textToInsert = "A long text that makes me think lalala"
                note.content.replaceSelection(&selection,  withCharacters: textToInsert)
            }

Thank you for the post and for your code. The unknown variable in your code is the Richnote class, which directly interacts with the underlying text view’s state through the @State private var selection binding.

Given that you are using the AttributedText library, the most effective approach to resolve this issue is to directly access the underlying NSTextView (on macOS) or UITextView (on iOS/iPadOS) that AttributedText.TextEditor encapsulates.

The AttributedText library provides a convenient method for this purpose. Could you please provide the class Richnote? I believe that the control is the source of the problem.

Albert Pascual
  Worldwide Developer Relations.

SwiftUI TextEditor: replaced text jumps outside current selection
 
 
Q