I'm trying to do a simple application in SwiftUI taking advantage of SwiftUI 2.0's new multiplatform project template, and I wish to add the option to collapse the sidebar as many other apps do.
I've got an extremely simple sidebar I did following the Fruta example project, and I tried adding a boolean state variable that controls whether the sidebar should show or not, but that doesn't work because when the sidebar is hidden, the main view is turned translucent.
On iPadOS, a button appears on top of the sidebar that allows to collapse it. How would I do this in macOS? Is there a way to natively achieve this in SwiftUI, or I'll need to resort to a UIKit workaround?
Please note I'm using macOS Big Sur, Xcode 12, and SwiftUI 2.0
Thanks in advance.
I've got an extremely simple sidebar I did following the Fruta example project, and I tried adding a boolean state variable that controls whether the sidebar should show or not, but that doesn't work because when the sidebar is hidden, the main view is turned translucent.
On iPadOS, a button appears on top of the sidebar that allows to collapse it. How would I do this in macOS? Is there a way to natively achieve this in SwiftUI, or I'll need to resort to a UIKit workaround?
Please note I'm using macOS Big Sur, Xcode 12, and SwiftUI 2.0
Thanks in advance.
Until (one would hope) Apple gets around to it, here's something that'll work.
Using Debug View Hierarchy in the debug toolbar, I found that a private NSSplitViewController is being used for layout. I opted to pass an action down the responder chain to toggle its associated sidebar:
One might also be able to use a package like Swift-Introspection to get a handle on the NSSplitViewController in your SwiftUI code and send the message more directly.
Using Debug View Hierarchy in the debug toolbar, I found that a private NSSplitViewController is being used for layout. I opted to pass an action down the responder chain to toggle its associated sidebar:
Code Block swift private func documentGroup() -> some Scene { return DocumentGroup(newDocument: Document()) { DocumentView() .toolbar { ToolbarItem(placement: .navigation) { Button(action: toggleSidebar, label: { Image(systemName: "sidebar.left") }) } } .environmentObject($0.document.store) } } private func toggleSidebar() { #if os(iOS) #else NSApp.keyWindow?.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil) #endif }
One might also be able to use a package like Swift-Introspection to get a handle on the NSSplitViewController in your SwiftUI code and send the message more directly.