Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Sidebar in SwiftUI NavigationView on macOS

I have a macOS Application with a NavigationView and want to have the default ToggleSidebar item in the toolbar of the window.

Currently I set the target of the ToolbarItem to the AppDelegate in toolbarWillAddItem(_) of the NSToolbarDelegate.

Inside of the AppDelegate I implemented

@objc func toggleSidebar(_ sender: Any) {
    ((window.contentView?.subviews.first?.subviews.first?.subviews.first as? NSSplitView)?.delegate as? NSSplitViewController)?.toggleSidebar(self)
}

This solution is working right now. If the implementation of SwiftUI will change this breaks.

So how can this be done in a better way?

like image 486
ricobeck Avatar asked May 13 '20 09:05

ricobeck


1 Answers

Since macOS Big Sur beta 4 you can add default sidebar commands with SwiftUI 2.0.

var body: some Scene {
    WindowGroup {
        NavigationView {
            Group {
                SidebarView()
                ContentView()
            }
        }
    }
    .commands {
        SidebarCommands()
    }
}

This code will add the "Toggle Sidebar" shortcut:

enter image description here

SidebarView code:

var body: some View {
    List {
        ForEach(0..<5) { index in
            Text("\(index)")
        }
    }
    .listStyle(SidebarListStyle())
}
like image 126
IrelDev Avatar answered Sep 23 '22 11:09

IrelDev