SwiftUI 樹形結(jié)構(gòu)展開與收起

11.png

可以控制獨自的展開與收起,也可以控制全部的展開與收起,全部代碼:

//
//  TreeListView.swift
//  TreeListView
//
//  Created by xuewu wei on 2022/9/4.
//

import SwiftUI

struct TreeListView: View {
    
    @StateObject var vm: NodeManager = NodeManager()
    @State var isExpanded: Bool = false
    
    var body: some View {
        
        VStack {
            List {
                ForEach($vm.list, id: \.self) { $item in
                    NodeGroup(node: item, childKeyPath: \.children, expandList: $vm.expandList) { item in
                        
                        if ((item.children?.isEmpty) != nil) {
                            Group {
                                Image(systemName: "folder.fill")
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .foregroundColor(.blue)
                                    .frame(width: 30, height: 30)
                                
                                Text(item.name)
                            }
                        }else {
                            HStack {
                                Image(systemName: "doc.fill")
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .foregroundColor(.blue)
                                    .frame(width: 30, height: 30)
                                
                                Text(item.name)
                            }
                        }
                        
                    }
                }
            }
            
            Button("全部展開/收起") {
                self.isExpanded = !self.isExpanded
                self.vm.expandAllOrCloseAll(self.isExpanded)
                print("=====: ",self.isExpanded, self.vm.expandList)
            }
        }
    }
}

struct TreeListView_Previews: PreviewProvider {
    static var previews: some View {
        TreeListView()
    }
}


struct NodeGroup<Node, Content: View>: View where Node: Hashable, Node: Identifiable, Node: CustomStringConvertible{
    @State var node: Node
    let childKeyPath: KeyPath<Node, [Node]?>
    @Binding var expandList: [String:Bool]
    @ViewBuilder let content: (_ item: Node) -> Content
    
    var body: some View {
        if node[keyPath: childKeyPath] != nil {
            let expanded = Binding<Bool>(get: {expandList[node.id as! String] ?? false}, set: {expandList[node.id as! String] = $0})
            DisclosureGroup(
                isExpanded: expanded,
                content: {
                    if expanded.wrappedValue {
                        ForEach(node[keyPath: childKeyPath]!) { childNode in
                            NodeGroup(node: childNode, childKeyPath: childKeyPath, expandList: $expandList) { item in
                                content(item)
                            }
                        }
                    }
                }) {
                    content(node)
                }
        } else {
            content(node)
        }
    }
}


// Mark: 數(shù)據(jù)
struct Node: Identifiable, Hashable, CustomStringConvertible {
    var id: String = UUID().uuidString
    var name: String
    var isExpanded: Bool = false
    var children: [Node]?
    var description: String {
        switch children {
        case nil:
            return "? \(name)"
        case .some(let children):
            return children.isEmpty ? "? \(name)" : "? \(name)"
        }
    }
}

class NodeManager: ObservableObject {
    @Published var list: [Node] = []
    @Published var expandList: [String:Bool] = [:] // 控制展開的字典值集合
    init() {
        self.list = [
            Node(name: "哈哈--1", children: [
                Node(name: "哈哈子集--1"),
                Node(name: "哈哈子集--2", children: [
                    Node(name: "哈哈子集--2--1"),
                    Node(name: "哈哈子集--2--2")
                ]),
                Node(name: "哈哈子集--3", children: [
                    Node(name: "哈哈子集--3--1"),
                    Node(name: "哈哈子集--3--2")
                ])
            ]),
            Node(name: "呵呵--1", children: [
                Node(name: "呵呵子集--1"),
                Node(name: "呵呵子集--2", children: [
                    Node(name: "呵呵子集--2--1"),
                    Node(name: "呵呵子集--2--2")
                ]),
            ])
        ]
        
        self.expandList = getExpandArr(arr: self.list)
        
    }
    
    // 根據(jù)數(shù)據(jù)抽出一個控制列表展開與收起的字典
    func getExpandArr(arr: [Node?]) -> [String:Bool] {
        
        var totals: [String:Bool] = [:]
        
        for item in arr {
            if let obj = item {
                // 保留舊鍵
                totals.merge([obj.id: false]) { current, _ in
                    current
                }
                if ((obj.children?.isEmpty) != nil) {
                    totals.merge(getExpandArr(arr: obj.children!)) { current, _ in
                        current
                    }
                }
            }
        }
        
        return totals
    }
    
    // 全部展開或者收起
    func expandAllOrCloseAll(_ flag: Bool) {
        for key in self.expandList.keys {
            self.expandList.updateValue(flag, forKey: key)
        }
    }
}

重點有三:

  1. 一個控制展開與收起的[String:Bool]字典 expandList 集合
  2. 此行代碼
let expanded = Binding<Bool>(get: {expandList[node.id as! String] ?? false}, set: {expandList[node.id as! String] = $0})

DisclosureGroup組件的isExpanded屬性是Binding<Bool>類>型,所以需要把控制展開與收起集合里字典對象包裝一下,以符合組件需要。

  1. 顯而易見就是樹形的遞歸調(diào)用了

中文資源太少了,大家努力豐富?。。。?/h1>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容