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?
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:
SidebarView code:
var body: some View {
List {
ForEach(0..<5) { index in
Text("\(index)")
}
}
.listStyle(SidebarListStyle())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With