Reading time: 1 min

This recipe shows how to add a toolbar with action buttons on the top of soft keyboard in SwiftUI. The end result looks like this:

Simulator%20Screen%20Shot%20-%20iPhone%20SE%20%282nd%20generation%29%20-%202021-08-19%20at%2020.31.05

This feature is available starting with SwiftUI 3 (iOS 15, macOS 12).

The pattern for adding the toolbar to the keyboard is the same as with toolbar setups, except you use a different placement, keyboard:

struct ContentView: View {
  var body: some View {
    NavigationView {
      VStack {
        Text("Hello, World!")
        TextField("Just some textfield", text: .constant(""), prompt: nil)
      }
      .padding()
      .navigationTitle("Toolbar Tester")
      .toolbar {
        // notice the new placement enum value
        ToolbarItemGroup(placement: .keyboard) {
          Button("My button") {
            // do something
          }
          Button("Another") {
            // do something else
          }
        }
      }
    }
  }
}
Styling Toolbar Buttons

You can apply both PrimitiveButtonStyle and custom ButtonStyles to toolbar buttons as well. Here are a few examples, with code just showing the buttons inside the ToolbarItemGroup:

Button("Plain") { }.buttonStyle(.plain)
Button("Borderless") { }.buttonStyle(.borderless)

results in:

Simulator%20Screen%20Shot%20-%20iPhone%20SE%20%282nd%20generation%29%20-%202021-08-19%20at%2020.30.30

Button("Bordered") { }.buttonStyle(.bordered)
Button("Bordered Prominent") { }.buttonStyle(.borderedProminent)

results in:

Simulator%20Screen%20Shot%20-%20iPhone%20SE%20%282nd%20generation%29%20-%202021-08-19%20at%2020.31.05

And here's one with a custom button style:

Button("Bordered") { }.buttonStyle(.bordered)
Button("Done") { }.buttonStyle(MyButtonStyle())

results in:

Simulator%20Screen%20Shot%20-%20iPhone%20SE%20%282nd%20generation%29%20-%202021-08-19%20at%2020.41.27

You can notice that, while the first two buttons are laid out with a spacer between them, all the subsequent buttons are crammed on the left-hand side of the toolbar.

Next Post Previous Post