SwiftUI DisclosureGroup 单独展开每个部分

Joh*_*ohn 4 ios swift swiftui

我正在使用 Foreach 和 DisclosureGroup 来显示数据。每个部分都可以展开/折叠。然而,它们都在同时扩展/折叠。

如何单独展开/折叠每个部分?

struct TasksTabView: View {
        
    @State private var expanded: Bool = false
        
    var body: some View {
        ForEach(Array(self.dict!.keys.sorted()), id: \.self) { key in
            if let tasks = self.dict![key] {
                DisclosureGroup(isExpanded: $expanded) {
                    ForEach(Array(tasks.enumerated()), id:\.1.title) { (index, task) in
                        VStack(alignment: .leading, spacing: 40) {
                            PillForRow(index: index, task: task)
                                .padding(.bottom, 40)
                        }.onTapGesture {
                            self.selectedTask = task
                        }
                    }
                } label: {
                    Header(title: key, SubtitleText: Text(""), showTag: true, tagValue: tasks.count)
                }.accentColor(.rhinoRed)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*e_E 13

您可以有一个Set包含所有扩展部分的键的文件。如果扩展了某个部分,请将其添加到集合中。然后当它折叠时将其移除。

代码:

@State private var expanded: Set<String> = []
Run Code Online (Sandbox Code Playgroud)
DisclosureGroup(
    isExpanded: Binding<Bool>(
        get: { expanded.contains(key) },
        set: { isExpanding in
            if isExpanding {
                expanded.insert(key)
            } else {
                expanded.remove(key)
            }
        }
    )
) {
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)