I am making an app in SwiftUI with a sidebar that will display hierarchical information. In this case, I am displaying a list of projects and each project will have some to-do lists inside.
My problem as you can see above is that all the sections are expanded by default when the app is launched and I would like that they be collapsed by default instead.
I am using List
with Section(header:content:)
for the sidebar and inside each section is an OutlineGroup
.
Here is the code I used
// Data source for the list
class MyEnvironmentObject: ObservableObject {
@Published var listItems = [
ListItem(name: "Project 1", children: [
ListItem(name: "List 1")
]),
ListItem(name: "Project 2", children: [
ListItem(name: "List 1"),
ListItem(name: "List 2")
]),
ListItem(name: "Project 3", children: [
ListItem(name: "Example list")
])
]
}
struct ContentView: View {
@EnvironmentObject var dataSource: MyEnvironmentObject
func listItem(for item: ListItem) -> some View {
Text(item.name)
}
var body: some View {
NavigationView {
List {
ForEach(dataSource.listItems) { item in
Section(header: listItem(for: item)) {
OutlineGroup(item.children ?? [], children: \.children) {
listItem(for: $0)
}
}
}
}
.listStyle(SidebarListStyle())
Text("Hello world")
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
I need a solution ideally using a List
with Section
, since I believe this is roughly what the built in apps like Files are using for their sidebar (which when opened have sections that are collapsed by default)
I was originally using this solution from SO which involved using DisclosureGroup
but I ran into issues formatting on phone/compact display because the List was having dividers by default and I couldn't disable those.
I then tried using a LazyVStack instead but it meant I wouldn't get a proper sidebar style especially on Big Sur.
This solution is so close but I am not sure how to get the sections to collapse automatically, so help would be much appreciated! ^-^