字典列表以列出视图SwiftUI [英] Array of dictionaries to list view SwiftUI
问题描述
我想用SwiftUI在列表视图中填充一系列字典。
I have an array of dictionaries I would like to populate in a list view with SwiftUI.
我过去曾经使用过循环,但是由于在View中不可能实现,因此我被困在该做什么。使用下面的代码,我可以获得部分结果。
I used for loops in the past but since that's not possible within a View I'm stuck as to what to do. I'm able to achieve partial results with the code below.
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]。
I'm looking to index through the entire Array of dictionaries and append them to the list, not just csvArray[0].
推荐答案
所以它像这样:
这是一个示例 csvArray
的值,这可以是任何东西,但是您应该将其余代码对更新为原始数据类型
This is an example of csvArray
, This could be anything but you should update the rest of the code duo to the original data type
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"]
]
这是您为单个字典编写的代码。但这将使用该字典,而不是硬编码的字典:
This is your code for a single dictionary. but this will take that dictionary instead of hardcoded one:
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])")
}
}
}
}
这是连接到原始阵列的列表生成器。我使用各节来说明数据结构的意义。
And this is the list builder connected to the original array. I used sections for the meaningfulness of the data structure.
struct ContentView: View {
var body: some View {
List {
ForEach(csvArray, id:\.self) { dict in
Section {
SectionView(dict: dict)
}
}
}
}
}
请注意,您无法中继字典中键值的顺序。因此,我建议您在填充列表之前进行一些排序
或使用其他数据结构,例如 class
或 struct
而不是简单的字典。
Note that you can't relay on the order of the key value in a dictionary. So I suggest you to do some sort
ing before populating the list or use another data structure like class
or struct
instead of a plain dictionary.
这篇关于字典列表以列出视图SwiftUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!