Hiding the Keyboard Using FocusState in SwiftUI
When you're entering text in a mobile app, it's a common expectation to tap outside of the text field to dismiss the keyboard.
I've been implementing this in a current project using SwiftUI, and was surprised to find it fairly undocumented online, so I thought I'd write up my solution.
There are articles talking about FocusState, which is available from iOS 15. This Hacking With Swift article is a great example. It shows how to use FocusState
to dismiss the on-screen keyboard when tapping a button.
But I haven't seen any articles talking about how to dismiss the keyboard using a background tap. And it's a really simple addition to the description in the Hacking With Swift approach.
Just set an onTapGesture
on the parent view:
@FocusState private var isTextFieldFocused: Bool
VStack { // or whatever your containing view is
TextField
... // configure as normal
.focused($isTextFieldFocused)
}
.onTapGesture {
isTextFieldFocused = false
}
This almost feels too easy, so if you have any feedback on this approach, please let me know on Mastodon or on Bluesky.
If you liked this article, please consider buying me a coffee to support my writing.
Published on 19 February 2025