swiftuiswiftui-texteditor

Detecting keyboard "submit button" press for TextEditor SwiftUI


On SwiftUI's TextField you can set an action for the return/submit button of the keyboard using the .onSubmit() modifier. How do you achieve the same with TextEditor? (.onSubmit() doesn't seem to work.)


Solution

  • You can use on change for the bound variable for the TextEditor like this:

        TextEditor(text: $text)
            .onChange(of: text) { _ in
                if !text.filter({ $0.isNewline }).isEmpty {
                    print("Found new line character")
                }
            }
    

    Realize that TextEditor does not have a submit button, per se. It is meant to accept an unlimited amount of all kinds of text.