NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to hide and show the sidebar programmatically

Paul Hudson    @twostraws   

Updated for Xcode 14.2

When using NavigationSplitView on macOS and iPadOS, SwiftUI lets us toggle showing the sidebar, content view, and detail view using the NavigationSplitViewVisibility enum.

This code sample shows all three variations:

struct ContentView: View {
    @State private var columnVisibility = NavigationSplitViewVisibility.detailOnly

    var body: some View {
        NavigationSplitView(columnVisibility: $columnVisibility) {
            Text("Sidebar")
        } content: {
           Text("Content")
        } detail: {
            VStack {
                Button("Detail Only") {
                    columnVisibility = .detailOnly
                }

                Button("Content and Detail") {
                    columnVisibility = .doubleColumn
                }

                Button("Show All") {
                    columnVisibility = .all
                }
            }
        }
    }
}

Download this as an Xcode project

There are four modes to choose from:

  • In .detailOnly mode, the detail view will take up all the available screen space for your app.
  • In .doubleColumn mode, you’ll see both the content and detail views.
  • In .all mode, the system will attempt to show all three views if they exist. In the case where you don’t have a content view (the middle view), it will only show two.
  • In .automatic mode, the system will do what it thinks is best based on the current device and orientation.

Note: providing the columnVisibility is done using a binding because your value will automatically be updated as the user interacts with your UI.

Although SwiftUI uses different names for these three parts of our split view interface, they match up directly with UIKit counterparts: the sidebar is “primary” in UIKit, content is “supplementary”, and detail is “secondary”.

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.