1

I am using FocusState to edit a TextField and then dismiss the keyboard with a 'done' submit label on the keyboard.

However, the .focused() modifier doesn't seem to work with a TextEditor on the same screen and therefore there is no 'done' button to dismiss the keyboard after typing into the TextEditor.

How can I create a single done button that dismisses the keyboard for both the focused text field and the text editor?

That is, I am looking for something like this:

struct ContentView: View {
  @FocusState var focusedInput: Input?
  @State private var fieldText: String = "Text field"
  @State private var editorText: String = "Text editor"
  
    var body: some View {
      VStack {
        TextField("", text: $fieldText)
          .focused($focusedInput, equals: .field)
          .submitLabel(.done)
        
        TextEditor(text: $editorText)
          .focused($focusedInput, equals: .editor)
          .submitLabel(.done)
      }
    }
}

enum Input {
  case field
  case editor
}
cbusch
  • 265
  • 2
  • 11
  • https://stackoverflow.com/questions/70318811/detecting-keyboard-submit-button-press-for-texteditor-swiftui ---- TextEditor does not support a submit button, because you can press return and add further text. You would have to add a real submit button next to it. – ChrisR Feb 04 '22 at 01:19

1 Answers1

1

Text Editor is not support the Submitlabel, you can create like add a button and when your put your value in textEditor then press button.

struct ContentView: View {
enum Input {
    case fieldText
    case editorText
    
}
@FocusState var focusedInput: Input?
  @State private var fieldText: String = "Text field"
  @State private var editorText: String = "Text editor"
  
    var body: some View {
      VStack {
        TextField("", text: $fieldText)
          .focused($focusedInput, equals: .fieldText)
          .submitLabel(.done)
        
        TextEditor(text: $editorText)
          .focused($focusedInput, equals: .editorText)
          .submitLabel(.done)
          Button("Submit") {
                          print("Tip:")
                          hideKeyboard()
                      }
          
      }
    }}



#if canImport(UIKit)
 extension View  {
func hideKeyboard() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)}`}#endif`
Saurabh Pathak
  • 879
  • 7
  • 10