Member-only story

SwiftUI — How to Add a ‘Done’ Button above Keyboard

Mia

This tutorial shows you how to create a ‘Done’ button that will display across the top of a SwiftUI keyboard so that users are able to manually dismiss the keyboard.

This is necessary to add on a number keypad as it doesn’t currently come with any built in way to dismiss it. On a regular keypad, users can press return to dismiss the keypad, however it creates a great experience to also give them a way to manually dismiss it.

TUTORIAL

  1. Add a @FocusState variable to your view. For example@FocusState private var keyboardFocused: Bool .
  2. On to your TextField within the view, add a .focused modifier that is bound to the keyboardFocused variable you created. eg

TextField(“Enter text”, text: $textInput) .focused($isTextFieldFocused)

3. On the view displaying the keyboard, add a toolbar with a toolbarItemGroup with placement of .keyboard and a button that will set the keyboardFocused state to false. eg

.toolbar {
ToolbarItemGroup(placement: .keyboard) {
// the Spacer will push the Done button to the far right of the keyboard as pictured.
Spacer()

Button(action: {
keyboardFocused = false
}, label: {
Text("Done")

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Mia
Mia

Written by Mia

Sharing Useful Resources, Explanations & Tutorials as I Learn iOS Development.

Responses (2)

Write a response

Article could have benefitted from a generic version with a view modifier that worked with enumerated focus states.

_keyboardFocused

why we should pass with _?
the compiler emits error?