Dismissing keyboard in SwiftUI

One challenge we have found with SwiftUI is dismissing the keyboard programmatically. Our workaround is to use a function like this:

Code Block
    func dismissKeyboard() {
        AppDelegate.currentWindow?.endEditing(true)
    }


And then a helper in AppDelegate to get the currentWindow:

Code Block
    static var currentWindow: UIWindow? {
        UIApplication.shared.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .map { $0 as? UIWindowScene }
            .compactMap { $0 }
            .first?.windows
            .filter { $0.isKeyWindow }.first
    }


Is there a better way to do this, whether in SwiftUI with iOS 13 or now with iOS 14?
You can send a UIResponder.resignFirstResponder action to UIApplication.shared:

Code Block swift
struct ContentView: View {
    @State private var text = ""
    var body: some View {
        VStack {
            TextField("Enter something here", text: $text).fixedSize()
            Button("Done") {
                let resign = #selector(UIResponder.resignFirstResponder)
                UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
            }
        }
    }
}

I wonder if this will continue to work in a SwiftUI-only app that uses the App protocol instead of UIApplication.
It's works using the App protocol. I believe UIApplication it's not going anywhere in the near future at least until there is a SwiftUI way to do all the things that are still not possible without UIKit.
Dismissing keyboard in SwiftUI
 
 
Q