Toggle Sidebar in Code using SwiftUI NavigationView on iPad

1.3k views Asked by At

I'm trying to utilize the built-in sidebar from SwiftUI 2.0 by using NavigationView like this:

NavigationView {
   MainView()
   ListView()
   DetailView()
}.navigationBarHidden(true)

But since I want to use my own Custom Back Button, I've hidden the NavigationBar and tried to toggle the sidebar with code which doesn't work.

self.presentationMode.wrappedValue.dismiss()

I've already seen a lot of solutions for macOS:

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

But I can't seem to find equivalent for iPad, thanks in advance.

2

There are 2 answers

0
Manny On

So this is not a good long term solution but if you are like me and 100% needed the native approach to work here's how it can be hacked. Using https://github.com/siteline/SwiftUI-Introspect you can find the right view controller in the hierarchy and set the display mode.

Text("Some View").introspectViewController { vc in
    guard let splitVC = vc.parent?.parent as? UISplitViewController else {
        return
    }

    splitVC.preferredDisplayMode = .oneBesideSecondary
}

This is BRITTLE but it works.

0
mattialerda On

I used this code to change the default sidebar settings:

extension UISplitViewController {
    open override func viewDidLoad() {
        super.viewDidLoad()

        self.preferredDisplayMode = .secondaryOnly
        self.preferredSplitBehavior = .overlay
    }
}

self exposes several sidebar methods and properties that can be used. I hope it will be useful!