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.)
Asked
Active
Viewed 3,130 times
6

unknown
- 788
- 9
- 24
3 Answers
9
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.

Yrb
- 8,103
- 2
- 14
- 44
-
Best solution i have found! I was looking for something like this to set the "focused field" to nil and save the text, so if anyone needs the same, you cand add text.removeLast() inside the IF statement, for saving the text without the space added when the user press the "return" button. – Alessandro Pace Feb 06 '22 at 19:12
1
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")
}
}

Estuardo Recargador
- 31
- 3
-2
Here is your solution:
onCommit: TextField calls onCommit closure when the user presses the Return key.

BLANDIN Florian
- 60
- 1
-
1OP was asking about a `TextEditor`, not a `TextField`. Further, `.onCommit` is deprecated in favor of `.onSubmit` which the OP discussed. – Yrb Dec 12 '21 at 16:14