Search code examples
swiftuiswiftui-list

Selection of the hierarchical list was not performed in SwiftUI


Hierarchical data was used with a list, but selection was not performed. I was unable to identify my mistake. I have added my code below for reference. Thanks in Advance

struct Node: Identifiable, Hashable {
    var id: String = UUID().uuidString
    var name: String
    var childNodes: [Node]?
}

struct HierarchicalData_List: View {
    @State var dataSource = [
        Node(name: "1", childNodes: [Node(name: "1.1")]),
        Node(name: "2", childNodes: [Node(name: "2.1", childNodes: [Node(name: "2.1.1")])])]
    @State var selectedNode: Set<Node> = []

    var body: some View {
        VStack {
            List(dataSource, children: \.childNodes, selection: $selectedNode) { node in
                Text(node.name)
            }
            .listStyle(InsetListStyle(alternatesRowBackgrounds: true))
        }
    }
}

Solution

  • The selection binding should be a Set of values that is the same type as the ID type of the data.

    Here, Node.id is of type String, so the selectedNode should be a Set<String>.

    @State var selectedNode: Set<String> = []
    

    If this is undesirable, you should make Node.id of type Node. That is, each Node uses itself as its ID.

    struct Node: Identifiable, Hashable {
        let uuid: String = UUID().uuidString
        var name: String
        var childNodes: [Node]?
        
        var id: Node { self }
    }
    

    Alternatively, you can pass the identity key path \.self to the id: parameter of List.init.

    List(dataSource, id: \.self, children: \.childNodes, selection: $selectedNode) { ... }