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.
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
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
mainWindow.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)
We can specify tool bar items on either sidebar or content.
.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
@main
struct AppWithSidebarAndToolbar: App {
var body: some Scene {
WindowGroup {
MainView()
}
}
}