How to show sidebar in SwiftUI for macOS

Issue #710

Starting from macOS 11, we can use List with SidebarListStyle inside NavigationView to declare master detail view. The SidebarListStyle makes list translucent. It automatically handles selection and marks selected row in list with accent color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct MainView: some View {
var body: some View {
NavigationView {
sidebar
ContentView()
}
}

private var sidebar: some View {
List {
Group {
Text("Categories")
.foregroundColor(.gray)
ForEach(categories) { category in
NavigationLink(destination: ContentView(category: category)) {
Label(category.name, systemImage: "message")
}
}
}

Divider()
NavigationLink(destination: SettingsView()) {
Label("Settings", systemImage: "gear")
}
}
.listStyle(SidebarListStyle())
}
}

If we use Section instead of just Group we get a nice dropdown arrow button to expand and collapse section

1
2
3
4
5
List {
Section(header: Text("Categories")) {
ForEach
}
}

Show and hide side bar

To toggle side bar, we can use toggleSidebar selector since for now, sidebar is backed by NSSplitViewController

1
mainWindow.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)

We can specify tool bar items on either sidebar or content.

1
2
3
4
5
6
7
8
.toolbar{
//Toggle Sidebar Button
ToolbarItem(placement: .navigation){
Button(action: toggleSidebar) {
Image(systemName: "sidebar.left")
})
}
}

For tool bar to work, we must use App and embed views inside WindowGroup

1
2
3
4
5
6
7
8
@main
struct AppWithSidebarAndToolbar: App {
var body: some Scene {
WindowGroup {
MainView()
}
}
}

Updated at 2021-01-06 20:43:40

Comments