Hello, I have a TextEditor in my app where users can enter a small amount of text using a default keyboard. I'm trying to change the keyboard though so that rather than having a grey return key, the button says Done.
I can achieve this with .submitLabel(.done) however the keyboard simply changes the button to blue and changes the label but when you press it, it still returns a new line in the TextEditor. I want to basically have the TextEditor lose focus when the done button is pressed.
You should make it more clear that this is a SwiftUI question
Anyhow, TextEditor doesn't have an .onSubmit() so you can't use that. You can use onChange(of: and check if the last character entered is a new line and remove focus when so
Kinda like this (not taking care of captures):
struct ContentView: View {
@State var text: String
@FocusState private var isFocused: Bool
var body: some View {
VStack {
TextEditor(text: $text)
.onChange(of: text) { _ in
if text.last?.isNewline == .some(true) {
text.removeLast()
isFocused = false
}
}
.focused($isFocused)
.submitLabel(.done)
}
.padding()
}
}
However depending on what you're after, you might want to use TextField instead. TextEditor is supposed to allow the user to enter any text they want, including new lines and by having a done button you're preventing them from doing so