字典数组转换为列表视图SwiftUI

4
我有一个字典数组,想要在SwiftUI中用列表视图显示。以前我使用循环,但由于在View中不可能使用,所以我不知道该怎么做。使用下面的代码,我能够实现部分结果。
struct Test : View {
let dict = csvArray[0]

var body: some View {
    let keys = dict.map{$0.key}
    let values = dict.map {$0.value}

    return List {

        ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}
}

我希望能够遍历整个字典数组并将它们附加到列表中,而不仅仅是csvArray[0]。

1个回答

7

这就像是关键值的部分,对吗?

那么就像这样做:

这是一个 csvArray 的例子,它可以是任何东西,但是你应该根据原始数据类型更新其余代码。

let csvArray = [
    [ "section0-key0": "section0-value0",
      "section0-key1": "section0-value1"],

    [ "section1-key0": "section1-value0",
      "section1-key1": "section1-value1"],

    [ "section2-key0": "section2-value0",
      "section2-key1": "section2-value1"]
]

这是你的单个字典代码。但是它将取代硬编码字典,使用该字典:
struct SectionView : View {
    @State var dict = [String: String]()

    var body: some View {
        let keys = dict.map{$0.key}
        let values = dict.map {$0.value}

        return  ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}

这是连接到原始数组的列表生成器。我使用节(section)来增强数据结构的可读性。
struct ContentView: View {
    var body: some View {
        List {
            ForEach(csvArray, id:\.self) { dict in
                Section {
                    SectionView(dict: dict)
                }
            }
        }
    }
}

请注意,在字典中,键值对的顺序是不可靠的。因此,在填充列表之前,我建议您进行一些排序,或者使用另一种数据结构,例如结构体,而不是普通的字典。


非常感谢您!我的目标是使用SwiftCSV导入CSV文件。每个CSV文件的标题都有不同的键“ Headers”,因此我不认为有一种方法可以为未知的内容构建结构体。排序可能有些棘手,但至少数据按其索引进行分组,而不是完全混乱。我可能能够弄清剩下的部分。非常感谢您的帮助! - Mdoyle1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接