Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Get sidebar isCollapsed state on macOS

I'm using a NavigationView to create a sidebar on macOS. I can toggle the sidebar using this code:

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

I'm now trying to display a label while the sidebar is hidden. Triggering this in the button will not work because the user can also hide the sidebar by resizing it.

There is an isCollapsed property on NSSplitViewItem and I assume this is what I might have to check for, but I have no clue how to access it with SwiftUI. Or is there another way to check for sidebar visibility?

like image 684
viedev Avatar asked Sep 16 '25 22:09

viedev


1 Answers

This has become a lot easier using the new NavigationSplitView in iOS 16+. For example:

@State private var splitViewVisibility = NavigationSplitViewVisibility.all

var body: some View {
    NavigationSplitView(columnVisibility: $splitViewVisibility) {
        SidebarView()
    } detail: {
        DetailVew()
    }
    .onChange(of: splitViewVisibility) { newValue in
        print(newValue)
    }
}
like image 52
Ashley Mills Avatar answered Sep 19 '25 21:09

Ashley Mills