How to create a sidebar to switch views in SwiftUI

This project will consist of our standard ContentView, a view we’ll create for the sidebar and as many views as the sidebar items (to keep things tidy).

Let’s start by creating the sidebar view. The sidebar will be made by creating a List and adding as many NavigationLink structures as we need.

Here’s a snipped of the SidebarView file:

struct SidebarView: View {
    var body: some View {
        List {
            // First item of the sidebar
            NavigationLink(destination: FirstView()){
                Text("First Item")
            }
            .font(.callout)
            .padding(.top, 10) .padding(.bottom, 10)
            // Second item of the sidebar            
            NavigationLink(destination: SecondView()){
                Text("Second Item")
            }
            .padding(.top, 10) .padding(.bottom, 10)
            .font(.callout)
        }
        .listStyle(SidebarListStyle())
        .frame(width: 150)
    }
}

The SidebarListStyle() will make our sidebar background translucent and blurred, a look that I personally really like. You can obviously add other items to the sidebar, I will just stick to two for clarity purposes.

Let’s now create two views called FirstView and SecondView, that we will link to the newly created NavigationLink items.

The content of those two files will be of your choice based on the purpose of your app.

Let’s jump now to the app’s ContentView. We now need to add together those pieces we created.

We can create a HStack to place the sidebar and our content side by side.

Here’s how it’s done:

struct ContentView: View {
    var body: some View {
        HStack {
            NavigationView {
                SidebarView()
                FirstView() // or whatever view you want to display first
            }
        }
        .frame(width: 650, height: 300)
        .padding()
    }
}

Wrap the SidebarView() and the first view you want to display – in our case FirstView() – in a NavigationView.
The NavigationView will allow our app to switch between the views we previously linked in the SidebarView file using NavigationLink items.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.