How do I create a toolbar in swiftUI

Asked on 2024-07-30

1 search

To create a toolbar in SwiftUI, you can use the toolbar modifier on a view. This allows you to add toolbar items and groups to your app's interface. Here's a basic example of how to create a toolbar in SwiftUI:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Hello, World!")
                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Button(action: {
                            // Action for the button
                        }) {
                            Image(systemName: "plus")
                        }
                    }
                    ToolbarItem(placement: .navigationBarTrailing) {
                        Button(action: {
                            // Action for the button
                        }) {
                            Image(systemName: "trash")
                        }
                    }
                }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example, the toolbar modifier is used to add two buttons to the navigation bar, one on the leading side and one on the trailing side.

For more advanced usage, such as adding toolbars to volumes in immersive spaces, you can refer to the session Dive deep into volumes and immersive spaces. This session covers how to add toolbars to volumes, including specifying ornament placements and adding buttons to perform different actions.

Relevant Sessions