Open/Close DisclosureGroup

Hi,

In Xcode 12.01

I am working on a View with an unknown number of DisclosureGroups in a List. I want to close any open DisclosureGroup when the user expands DisclosureGroups.

For example here in this test code I have 100 DisclosureGroups in List and the code will close any open.
Code Block
import SwiftUI
struct TestView: View {
    @State var selectedStrength = 0
    @State var expaned = Array(repeating: false, count: 100)
    var strengths = Array(repeating: "Test", count: 100)
    var body: some View {
        List {
            ForEach(0 ..< strengths.count, id: \.self) { strIndex in
                DisclosureGroup(isExpanded: $expaned[strIndex], content: {
                    Text("Group open \(strIndex)")
                } , label: {
                    Text("Group \(strIndex)")
                }).onChange(of: expaned[strIndex]) { _ in
                    if expaned[strIndex] {
                        for index in expaned.indices {
                            if index != strIndex {
                                expaned[index] = false
                            }
                        }
                    }
                }
            }
        }
    }
}


But how to handle this if the number number of DisclosureGroups not known?

Replies

did you actually find a solution to this?

I'm curious about this as well. I have a certain count of a variable I know will need disclosure groups on a per view basis. However, I can't create a variable for it in the struct since it's only available in the body. I'm a bit of a newbie to swift so could just be doing things wrong, but this seems overly difficult.

I want each disclosure group to expand separately from the others, so thought I might just be able to make an array of Bools in an array for each entry that will have a disclosure group. Didn't work.

I can do one that applies globally to all items in one disclosure group very easily of course, and that's what I'll do until I can get a better aesthetic fix.