BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

How to create a toolbar and add buttons to it

Paul Hudson    @twostraws   

Updated for Xcode 14.1

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")
                }
            }
        }
}
Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.