How to create a toolbar and add buttons to it
About 2 min
How to create a toolbar and add buttons to it 관련
SwiftUI by Example
Back to Home
How to create a toolbar and add buttons to it | SwiftUI by Example
How to create a toolbar and add buttons to it
Updated for Xcode 15
SwiftUI's toolbar()
modifier lets us place bar button items anywhere in the top or bottom space, but only when our view is embedded inside a NavigationStack
.
If you want to place buttons into a toolbar at the bottom of the screen, use toolbar()
then create a ToolbarItem
with the placement of .bottomBar
, like this:
NavigationStack {
Text("Hello, World!").padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button("Press Me") {
print("Pressed")
}
}
}
}
To get more than one button, use ToolbarItemGroup
instead of a simple ToolbarItem
, then place multiple buttons inside there:
NavigationStack {
Text("Hello, World!").padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Button("First") {
print("Pressed")
}
Button("Second") {
print("Pressed")
}
}
}
}
If you want to separate buttons inside a ToolbarItemGroup
, add a spacer view wherever you want it. For example, this will place one button on the left edge of the toolbar, and one on the right edge:
NavigationStack {
Text("Hello, World!").padding()
.navigationTitle("SwiftUI")
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Button("First") {
print("Pressed")
}
Spacer()
Button("Second") {
print("Pressed")
}
}
}
}
Similar solutions…
How to let users customize toolbar buttons | SwiftUI by Example
How to let users customize toolbar buttons
SwiftUI tips and tricks | SwiftUI by Example
SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example
All SwiftUI property wrappers explained and compared
How to add a toolbar to the keyboard | SwiftUI by Example
How to add a toolbar to the keyboard
Building a menu using List | SwiftUI by Example
Building a menu using List