focustextfieldswiftuikeypress

How can I remove Textfield focus when I press return or click outside Textfield?


How can I remove Textfield focus when I press return or click outside Textfield? Note that this is SwiftUI on macOS.

If I do this:

import SwiftUI
    
struct ContentView: View {
    @State var field1: String = "This is the Text Field View"
      
    var body: some View {
        VStack{
          Button("Press") {
            print("Button Pressed")
          }
          
          TextField("Fill in Text", text: Binding(
            get: { print("get") ; return self.field1 },
            set: { print("set") ; self.field1 = $0 }
            )
          )
        }
    }
}

then click into the TextField and edit it then click on the Button the TextField does not lose focus. How can I make it exit editing mode and lose focus?

I would also like to lose focus from the TextField if I press Return. I used the Binding initialiser with get and set because I thought I could somehow intercept keypresses and detect the 'Return' character but this doesn't work.


Solution

  • Here are possible variants

    import SwiftUI
    import AppKit
    
    struct ContentView: View {
      @State var field1: String = "This is the Text Field View"
    
      var body: some View {
        VStack{
          Button("Press") {
            print("Button Pressed")
              NSApp.keyWindow?.makeFirstResponder(nil)
          }
    
          TextField("Fill in Text", text: Binding(
            get: { print("get") ; return self.field1 },
            set: { print("set") ; self.field1 = $0 }
            ), onCommit: {
                DispatchQueue.main.async {
                    NSApp.keyWindow?.makeFirstResponder(nil)
                }
          }
          )
        }
      }
    }