iPadOS - Close sidebar programmatically in SwiftUI
Asked Answered
T

1

6

I'm making an app that runs perfectly in iOS and iPadOS with SwiftUI, but in iPad there is a side bar that appears when I use .navigationViewStyle(DoubleColumnNavigationViewStyle()) modifier in my NavigationView and I'm wondering if is there a way to close the side bar programmatically, usually users can close the sidebar by touching the button from top left of the screen, but that's user interaction. It's possible to close the side bar directly in code?

Find out that SwiftUI-Introspect can be used to accomplish this requirement, but I wanted to do it without external libraries.

This is a simple code to reproduce the sidebar in iPadOS:

import SwiftUI
@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            NavigationView {
                if UIDevice.current.userInterfaceIdiom == .pad {
                    Text("Sidebar here")
                    Text("Content here")
                }
            }.navigationViewStyle(DoubleColumnNavigationViewStyle())
        }
    }
}
Thoroughpaced answered 3/3, 2021 at 20:17 Comment(0)
B
3

I tried with this code and it worked:

import SwiftUI

struct TestView: View {
    static var uiSplitViewController: UISplitViewController? = nil
    
    var body: some View {
        NavigationView {
            Text("Sidebar")
        
            VStack {
                Button(action: {
                    TestView.uiSplitViewController?.hide(.primary)
                }, label: {
                    Text("Hide")
                })
                
                Button(action: {
                    TestView.uiSplitViewController?.show(.primary)
                }, label: {
                    Text("Show")
                })
            }
        }
        
    }
}

extension UISplitViewController {
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        if (TestView.uiSplitViewController == nil) {
            TestView.uiSplitViewController = self
        }
    }
}

I don't know if that is the correct way or not. What I did was extend UISplitViewController and save its instance in the view, so I can use it to hide or show the sidebar. I hope can be useful!

Blackmarketeer answered 1/3, 2022 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.