UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: .toolbar & ToolBarItemGroup & spacing

Forums > 100 Days of SwiftUI

If I do this:

struct ContentView: View {
    var body: some View {
        NavigationView {
            Form {
                Text("Hello, world!")
            }
            .toolbar {
                ToolbarItemGroup(placement: .bottomBar) {
                    HStack {
                        Button("Delete") {
                            print("delete")
                        }
                        Spacer()
                        Button("Save") {
                            print("save")
                        }
                    }
                }
            }
        }
    }
}

I get the Delete and Save buttons on the bottom, one at the far left and one at the far right. If I remove: (placement: .bottomBar) they show up at the top but jammed next to each other on the top with a tiny space in between. If I add additional Spacer(), each one only adds a tiny space. Why isn't Spacer() working the same way and how do I get the top buttons to show up like the bottom buttons, spaced apart?

2      

Here's how you can make the same layout in the navigation bar:

.toolbar {
    ToolbarItem(placement: .navigationBarLeading) {
        Button("Delete") {
            print("delete")
        }
    }
    ToolbarItem(placement: .navigationBarTrailing) {
        Button("Save") {
            print("save")
        }
    }
}

Spacer is working, it's just that the space the HStack takes up is smaller than it is at the bottom.

Per the docs for ToolbarItemPlacement.automatic (i.e., the default setting if you don't supply an explicit one):

In iOS, iPadOS, and tvOS, the system places items in the trailing position of the navigation bar.

So all of the items in the ToolbarIItemGroup have to fit into the trailing slot, so there isn't a lot of room to spread them out with a Spacer.

2      

Thanks for the reply. So many things to learn.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.