Ad

Placing The Toggle Sidebar Button On The Sidebar Toolbar

- 1 answer

I have a three column layout macOS application with the first being the sidebar. I have a button that toggles that enabling the user to hide the sidebar.

On Xcode and other macOS, the toggle sidebar button resides on the toolbar on top of the sidebar, and becomes part of the main toolbar when the sidebar is hidden.

For example, open sidebar on Xcode:

enter image description here

And when you hide the sidebar:

enter image description here

I have added the toolbar with the toggle sidebar to the view containing my sidebar, and another toolbar to the second column, but still toggle sidebar appears on the main toolbar, on top of the second column.

Am I missing anything? Here's the code:

    // sidebar view, first of three columns
    struct ContentView: View {
       @State var selection: Set<Int> = [0]
       var body: some View {
          NavigationView {
              List(selection: self.$selection) {
                    NavigationLink(destination: AllData()) {
                        Label("All Data", systemImage: "note.text")
                    }
                    .tag(0)
                    Label("Trash", systemImage: "trash")
                }
                .listStyle(SidebarListStyle())
                .toolbar {
                    ToolbarItem(placement: .navigation) {
                        Button(action: toggleSidebar, label: {
                                Image(systemName: "sidebar.left") }).help("Toggle Sidebar")
                    }
                }
          }
       }
       func toggleSidebar() {
            NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
        }
    }

// second column view, with the rest of the toolbar
struct AllData: View {
   var body: some View {
       NavigationView {
           List(filteredData) {
                // list items here.
           }
           .toolbar {
             ToolbarItem(placement: .automatic) {
                Button("Press Me") {
                    print("Pressed")
                }
             }
             ToolbarItem(placement: .automatic) {
                Button("Press Me too") {
                    print("Pressed too")
                }
             }
         }
       }           
   }
}
Ad

Answer

try this:

 ToolbarItem(placement: .primaryAction) {

enter image description here

Ad
source: stackoverflow.com
Ad