2

如何迭代列表中的两个数组:

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)")
    }
4

4 回答 4

3

简单一点

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)")
    }
}
于 2019-11-28T17:40:03.370 回答
1

我认为这有点麻烦,并且创建了不需要的类型。出于这个原因,SwiftUI 有 ForEach 语句。代码也可以如下所示:

导入 SwiftUI

结构内容视图:查看{

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)
    }
}

}

结果如下所示: 在此处输入图像描述

当然,两个数组需要具有相同数量的元素。

于 2020-05-30T19:31:50.537 回答
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)")
}
于 2019-11-28T17:00:10.093 回答
1

或者,如果您想获得两个不错的列,您可以按照您想要的方式进行操作:

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)
        }
    }
}    

然后你会得到这样的结果: 在此处输入图像描述

于 2020-05-30T20:59:56.317 回答