Detecting keyboard "submit button" press for TextEditor SwiftUI

Viewed 1183

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.)

3 Answers

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.

Another way to know when the user created a new line:

TextEditor(text: $text)
            .onChange(of: text) { string in
                for char in string
                {
                    if char() == "\n"
                    {
                        print("Found new line character")
                    }
                }
            }

Yrb answer and this one works well but once there's a new line found and every time a new character is added to the TextEditor you're doing the same action: print("Found new line character")

If you want to know every time user presses enter or creates a new line this one is a better solution for you:

TextEditor(text: $text)
            .onChange(of: text) { string in
                if string.last == "\n"
                {
                    print("Found new line character")
                }
            }

Here is your solution:

onCommit: TextField calls onCommit closure when the user presses the Return key.

Related