Home > Blockchain >  Recursive Disclosure Groups in SwiftUI
Recursive Disclosure Groups in SwiftUI

Time:01-14

I would like to show a directory structure with all nodes expanded in SwiftUI. I found an example of a recursive disclosure view structure on the internet.

The view:

struct TracksDirOutlineView<Node>: View where Node: Hashable, Node: Identifiable, Node: CustomStringConvertible{
let node: Node
let childKeyPath: KeyPath<Node, [Node]?>
@State var isExpanded: Bool = true

var body: some View {
    GeometryReader { geometry in
        if node[keyPath: childKeyPath] != nil {
            DisclosureGroup(
                isExpanded: $isExpanded,
                content: {
                    if isExpanded {
                        ForEach(node[keyPath: childKeyPath]!) { childNode in
                            TracksDirOutlineView(node: childNode, childKeyPath: childKeyPath, isExpanded: isExpanded)
                        }
                    }
                },
                label: { Text(node.description) })
        } else {
            Text(node.description)
        }
    }
}

}

The model / view model:

    struct FileItem: Hashable, Identifiable, CustomStringConvertible {
    var id: Self { self }
    var name: String
    var children: [FileItem]? = nil
    var description: String {
        switch children {
        case nil:
            return "           
  • Related