SwiftUI iOS16表,带有可扩展子项(类似于DisclosureGroup)

5ktev3wc  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(152)

我目前正在将旧的SwiftUI代码迁移到iOS 16。以前我使用一个List和DisclosureGroups来创建一个表(下面的代码示例)。
理想情况下,我想使用iOS 16表自动创建和大小的列,而不是强制一个固定的大小有一个适当的列布局。

List {
    ForEach(someObject, id: \.id) { vm in
        DisclosureGroup {
            Disclosure(viewModel: mv.items)
        } label: {
            Row(viewModel: vm)
        }
    }
}

表格是否提供了这样的显示/折叠功能?

编辑

我忘了说我想显示的子项不适合父表列。这将是一个自定义的UI,为了简化,让我们说只是一个Text使用全宽度

w80xi6nr

w80xi6nr1#

据我所知,没有将DisclosreGroup与Table一起实现,但您可以模拟其功能,这里是一个开始:

struct TableItem: Identifiable, Equatable {
    let id = UUID()
    let name: String
    let value1: Int
    let value2: Int
    let value3: Int
    var expanded: Bool = false
    let children: [TableItem]
}

struct ContentView: View {
    
    @State private var someObjects: [TableItem] = (1...30).map {
        TableItem(name: "Parent \($0)",
                  value1: 0, value2: 0, value3: 0,
                  children: (1...5).map {
            TableItem(name: "child \($0)",
                      value1: Int.random(in: 0..<100), value2: Int.random(in: 0..<100), value3: Int.random(in: 0..<100),
                      children: [])
            
        }
        )
    }
    
    var body: some View {
        
        Table(of: TableItem.self) {
            TableColumn("Name") { row in
                Text(row.name).fontWeight(row.children.isEmpty ? .regular : .bold)
                    .onTapGesture {
                        if let index = someObjects.firstIndex(of: row) {
                            withAnimation {
                                someObjects[index].expanded.toggle()
                            }
                        }
                    }
            }

            TableColumn("Value 1") { row in
                Text(row.value1.formatted())
            }

            TableColumn("Value 2") { row in
                Text(row.value3.formatted())
            }

            TableColumn("Value 3") { row in
                Text(row.value3.formatted())
            }

        } rows: {
            ForEach(someObjects, id: \.id) { row in
                TableRow(row)
                if row.expanded {
                    ForEach(row.children) { child in
                        TableRow(child)
                    }
                }
            }
        }
    }
}

相关问题