iosswiftuikeyboarddismisssearchable

How do dismiss keyboard on .searchable while search bar is still focused?. [SwiftUI]


I added .searchable and it is working fine. But I want to show another view while the search is still focused and on the navigation bar.

If I use

@Environment(\.dismissSearch) private var dismissSearch

It will completely dismiss the search and clean the search text. I don't want that to happen.

By clicking Search button on keyboard, it will dismiss the keyboard. But I want to do it programmatically.

so any workaround to dismiss the keyboard while search bar is still focused? Thanks.

enter image description here


Solution

  • Add this to your code

    extension View {
        func hideKeyboard() {
            let resign = #selector(UIResponder.resignFirstResponder)
            UIApplication.shared.sendAction(resign, to: nil, from: nil, for: nil)
        }
    }
    

    Then you should be able to call hideKeyboard() from within any view and that will dismiss the keyboard.