macosbuttonswiftuisidebar

SwiftUI Sidebar with collapsing Button


I try to add an "add" button to a sidebar within a NavigationSplitView of a macos apps same as found in the Xcode window. Using this code within the sidebar-view does create the button at the top of the view but it is NOT going to hide when collapsing the sidebar.

.toolbar {
        ToolbarItem(placement: .primaryAction) {
            Button(action: addUser) {
                Label("Create New User",
                      systemImage: "person.crop.circle.badge.plus")
            }
            .help("New User")
        }

How to create a sidebar-view specific button at the bottom that sticks to the sidebar and is hidden when the sidebar is collapsing? Thanks!

enter image description here


Solution

  • In SwiftUI for macOS, none of the ToolbarItemPlacement options available for positioning toolbar items corresponds to the bottom of the sidebar.

    However, you can achieve something similar by placing controls within your view. While you could potentially place them in a ZStack or a VStack, an alternative (and some might say more idiomatic) approach is to use .safeAreaInset. For example:

    struct ContentView: View {
        var body: some View {
            NavigationSplitView {
                List {
                    ForEach(1..<100, id: \.self) { i in
                        Text("Sidebar Item \(i)")
                    }
                }
                .safeAreaInset(edge: .bottom) {
                    HStack {
                        Button("Add", systemImage: "plus") { }
                        Spacer()
                    }
                    .controlSize(.small)
                    .labelStyle(.iconOnly)
                    .padding(8)
                }
            } detail: {
                Text("Detail")
            }
        }
    }
    

    An example of a sidebar with a bottom bar using .safeAreaInset