Keyboard Toolbar in SwiftUI
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:
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 ButtonStyle
s 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:
Button("Bordered") { }.buttonStyle(.bordered)
Button("Bordered Prominent") { }.buttonStyle(.borderedProminent)
results in:
And here's one with a custom button style:
Button("Bordered") { }.buttonStyle(.bordered)
Button("Done") { }.buttonStyle(MyButtonStyle())
results in:
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.