Did you know? How to hide keyboard in SwiftUI?

iOS 15 have new property wrapper: @FocusState. This is exactly like a regular @State property, except it’s specifically designed to handle input focus in our UI.

In this tutorial we will get to know that how to hide keyboard or you can say how to work with the @FocusState in SwiftUI.

Here is the sample code for adding Done button in the Toolbar and hide keyboard on that button click.

private enum Field: Int, CaseIterable {
case username, password
}
@State private var username: String = ""
@State private var password: String = ""
@FocusState private var focusedField: Field?
var body: some View {
NavigationView {
Form {
TextField("Username", text: $username)
.focused($focusedField, equals: .username)
SecureField("Password", text: $password)
.focused($focusedField, equals: .password)
}
.toolbar {
ToolbarItem(placement: .keyboard) {
Button("Done") {
focusedField = nil
}
}
}
}
}
Hide keyboard in SwiftUI
Sample Code for Keyboard Handling

Conclusion

Let me know if you have any questions, comments, or feedback – either via Twitter.

Stay Safe At Home. Learn Something New. Share To The World.
Happy Coding 🙂