swiftuiswiftui-listexpandable

What are the requirements for a free expandable List in SwiftUI?


Somewhere in my code I have this pretty standard list with sections:

var body: some View {
    List {
        ForEach(userData.groupedBookings) { group in
            Section(header: Text(group.key)) {
                ForEach(group.items) { booking in
                    LessonRow(booking: booking)
                }
            }
        }
    }
}

Somehow with this code the sections are expandable/collapsable, which makes me happy, but I don't know why. I'm especially frustrated because I want to reproduce this behavior elsewhere with similar code and don't get the expand / collapse.

What are the requirement to automatically get this?


Solution

  • It is activated by sidebar list style (which in some conditions are considered as default), which you can use explicitly

    List {
        ForEach(userData.groupedBookings) { group in
            Section(header: Text(group.key)) {
                ForEach(group.items) { booking in
                    LessonRow(booking: booking)
                }
            }
        }
    }
    .listStyle(SidebarListStyle())
    

    as alternate you can use DisclosureGroup explicitly to have disclosure behavior for sections, like in https://stackoverflow.com/a/63228810/12299030