In my app I have a textfield
TextField("", text: $messageText, axis: .vertical)
.submitLabel(.search)
.onSubmit{print("submitted")}
I want the return key to say "search" which it does with .submitLabel, and I want it to submit the entered text ($messageText) to my api (take action) and dismiss when search button is pressed, instead of simply adding another line to the text field.
Testing this by printing "submitted" shows no action has been taken in the console.
I have a button on the UI that does this:
Button {
sendMessage()
messageText = ""
isTyping.toggle()
isResponding.toggle()
}
I want the return button, now labeled "search" to take the action the Button is taking. I'm trying to use onSubmit but it does not get called, it enters another line in the textfield. I have created new views and tried a simple implementation of at textfield and onsbumit and I still only get an extra line added to the text field, and no on submit action.
How do I get the return/search key on a keyboard for the textfield to take action? I am using Xcode 14.2.
For reference here is the complete view block of code.
@ViewBuilder
func typingView() -> some View {
VStack {
HStack {
TextField("", text: $messageText, axis: .vertical)
.submitLabel(.search)
.onSubmit{ print("submitted")}
.padding()
.keyboardType(.webSearch)
.ignoresSafeArea(.keyboard)
.font(.system(size: 26, weight: .semibold))
.focused($typingInFocus)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
self.typingInFocus = true
}
}
Button {
sendMessage()
messageText = ""
print("sent type")
isTyping.toggle()
print(isTyping)
isResponding.toggle()
}
label: {
Image(systemName: messageText == "" ? "circle" : "arrow.up.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 25, height: 25)
.scaleEffect(messageText == "" ? 1.0 : 1.3)
.foregroundColor(messageText == "" ? .white.opacity(0.0) : .white)
.padding()
}
.disabled(messageText == "")
}
}
}