0

I have a foreach with a list of strings, Every element will have an expandable view. I want for all of them to start already expanded. And I also want to collapse/expand them individually.

@State myLists = ["list1", "list2", "list3"]

ForEach(myLists, id: \.self){myList in

     DisclosureGroup(myList){

                Text(myList)

     }

}

I want all of them to start already expanded, and to collapse them individually.

I ve tried multiple links but most of them do not work unfortuately.

SwiftUI DisclosureGroup Expand each section individually -This one works but it start with all of them closed.

dhaval123
  • 107
  • 11

1 Answers1

1

You can make another View to do that, e.g.

struct ContentView: View {
    let myLists = ["list1", "list2", "list3"]
    
    var body: some View {
        ForEach(myLists, id: \.self){ myList in
            ContentView2(text: myList)
        }
    }
}

struct ContentView2: View {
    let text: String
    @State private var expanded = true
    
    var body: some View {
        DisclosureGroup(text, isExpanded: $expanded){
            Text(text)
        }
    }
}

Note id: \.self is not valid for dynamic @State you need to use a real id of the data otherwise it'll crash when it changes.

malhal
  • 26,330
  • 7
  • 115
  • 133