macosswiftui

SwiftUI: How to change visibility of details NavigationSplitView?


I'd like to hide/show the details split view of a NavigationSplitView on macOS.

However NavigationSplitViewVisibility does not seem to have such option. Changing .navigationSplitViewColumnWidth() or .frame() has no effect on the details view although it works well with the content and list view.

NavigationSplitView {
  List(selection: $selection)
} content: {
  content(for: selection)
} detail: {
  Text("Detail")
}

Did Apple forget to implement such a feature? :/


Solution

  • Trying to figure out an answer to the same question for myself, I have come to this conclusion:

    A NavigationSplitView is meant to display a hierarchy where each next level (sidebar, content, detail) is a sub-level of of the previous one. In such a structure you might always want to show a detail view, even it is empty.

    In any case, even if that is not the logic, the way to make the "detail" part hidable would be by implementing a two-column navigation with NavigationSplitView and adding a DetailView, enclosing all of these in an HStack and making the DetailView visibility conditional:

    struct MyView: View {
    
    @State var showingDetail: Bool = true
    
    var body: some View {
        HStack {
            NavigationSplitView {
                SidebarView()
            } detail: {
                ContentView()
            }
    
            if  showingDetail {
                DetailView()
            }
        }
        .toolbar {
            Toggle(isOn: $showingDetail) {
                Image(systemName: "sidebar.trailing")
            }
            .toggleStyle(.button)
        }
    }
    

    }