如何在列表中迭代两个数组:
struct ContentView: View {
let colors = ["red", "green", "blue"]
let names = ["John", "Apple", "Seed"]
var body: some View {
VStack {
List(colors, id: \.self) { color in
Text(color)
}
}
}
}
例如,我需要具备:
Text("\(color) - \(animal)")
我的代码将是这样(我知道这是错误的,但这就是这个主意):
List(colors, animals id: \.self) { color, animal in
Text("\(color) - \(animal)")
}
答案 0 :(得分:2)
简单一点
var body: some View {
VStack {
List(Array(zip(colors, names)), id: \.self.0) { (color, name) in
Text("\(color) - \(name)")
}
}
}
更新:为非等长数组添加了变体
这当然有点复杂,但可能会有所帮助
var body: some View {
VStack {
ListOfPairs()
}
}
private func ListOfPairs() -> some View {
var iter = names.makeIterator()
let container = colors.reduce(into: Array<(String,String)>()) { (result, color) in
result.append((color, iter.next() ?? "None" )) // << placeholder for empty
}
return List(container, id: \.self.0) { (color, name) in
Text("\(color) - \(name)")
}
}
答案 1 :(得分:1)
您可以将这两个数组作为每个项目的对象,因为它们彼此相关。可以这样:
struct Object: Identifiable {
let id: UUID = UUID()
let color: String
let name: String
}
let objects = [Object(color: "red", name: "John"),
Object(color: "green", name: "Apple"),
Object(color: "blue", name: "Seed")]
并按如下方式使用:
List(objects) { object in
Text("\(object.color) - \(object.name)")
}
答案 2 :(得分:0)
我认为这有点麻烦,创建不必要的类型。因此,SwiftUI具有ForEach语句。代码也可以像这样:
导入SwiftUI
struct ContentView:查看{
let colors = ["red", "blue", "black", "purple", "green"]
let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]
var body: some View {
List {
ForEach(0 ..< colors.count) {
Text("Name \(self.names[$0]) has favorite color \(self.colors[$0]).")
}
.onDelete(perform: deleteRow)
}
}
}
当然,两个数组都必须具有相同数量的元素。
答案 3 :(得分:0)
或者,如果您想获得两个漂亮的列,则可以按自己的方式进行操作:
import SwiftUI
struct ContentView: View {
let colors = ["red", "blue", "black", "purple", "green"]
let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]
var body: some View {
HStack {
List(names, id: \.self) { name in
Text(name)
}
.frame(width: 130)
List(colors, id: \.self) { color in
Text(color)
}
.frame(width: 160)
}
}
}