Sidebar and Label

Sidebar and Label

Setting up a sidebar navigation for iOS 14 and macOS

With SwiftUI, you can easily add a sidebar that shows up with a tap. This is done with the help of NavigationView. The items inside NavigationView act as links.

Downloads

To follow this course, you can download the source file, which will help you compare your progress.

Getting Started

Let's start by creating a new file. Press Cmd + N and select SwiftUI View. Name it Sidebar and resume the preview.
swiftui-section4-1

Label

  • From the insert menu, drag and drop the label modifier replacing the text one
  • Replace the parameter values of the modifier with:

var body: some View {
Label("Courses", systemImage: "book.closed")
}
swiftui-section4-2

Sidebar

Now, to create a sidebar menu, all we need to do is embed the element inside a list. To do so:

  • Cmd + Click the label and select Embed in VStack. Rename VStack to List
  • Feel free to add in more items according to your preference or copy the ones below
  • Add in the listStyle modifier to the list as follows:

List {
Label("Courses", systemImage: "book.closed")
Label("Tutorials", systemImage: "list.bullet.rectangle")
Label("Livestreams", systemImage: "tv")
Label("Certificates", systemImage: "mail.stack")
Label("Search", systemImage: "magnifyingglass")
}
.listStyle(SidebarListStyle())
swiftui-section4-3

Navigation View

Since, we're missing the navigation, let's add that in now.

  • Embed list in a VStack and rename VStack to NavigationView
  • Below the listStyle modifier, add in:

.navigationTitle("Learn")
swiftui-section4-4

Navigation Link

  • Firstly, embed the first label in a VStack. Rename the VStack to NavigationLink
  • Add in a destination parameter to it so that when you click on the link, it leads you to CoursesView

NavigationLink(destination: CoursesView()) {
Label("Courses", systemImage: "book.closed")
}
swiftui-section4-5

Content

You can also test how the sidebar looks on an iPad by changing the device to iPad Pro 11-inch. By default, the content isn't loaded. To fix this, add in the following, right after list

NavigationView {
// List
CoursesView()
}
swiftui-section4-6

Testing

To test in landscape mode, press Cmd + R or click the play button on the top bar. This will open the iOS simulator and build the app.
swiftui-section4-7

Initial Screen

Currently, when you build the app, you'll notice that it shows the card by default. This is happening because we haven't set up an initial screen yet. To set it up, do the following:

  • Head over to DesignCodeCourseApp.swift
  • Replace ContentView() with the following and press Cmd + R again to see the changes

Sidebar()
swiftui-section4-8

Navigation Title

Lastly, we'll set a navigation title for the CoursesView as well. To do so:

  • Head over to CoursesView.swift
  • Here, right after the listStyle modifier, add in the navigationTitle modifier

// List
.navigationTitle("Courses")
swiftui-section4-9