Collapse sidebar in SwiftUI (Xcode 12)

This worked for me - https://developer.apple.com/forums/thread/651807

struct SwiftUIView: View {
    var body: some View {
        NavigationView{

        }.toolbar {
            ToolbarItem(placement: .navigation) {
                Button(action: toggleSidebar, label: {
                    Image(systemName: "sidebar.left")
                })
            }
        }
    }
}

func toggleSidebar() {
        NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

It shows in the views on iOS so you will need some conditions for macOS only.


Apple provide NSToolbarToggleSidebarItemIdentifier which perform the toggleSidebar(_:) method.

.onAppear {
    NSApp.keyWindow?.toolbar?.insertItem(withItemIdentifier: .toggleSidebar, at: 0)
}

This way will appear a button in your toolbar which action will invoke the sidebar toggle and it works perfectly.