我有一个Down代码,该代码在ForEach循环中制作了一些Text,该循环使用(int:.self)Int,但是在这种情况下,我们生成的(id = UUID())将被忽略!而且ForEach可以使用一些内部Int编号!我们如何强制ForEach将我们构建的UUID用作ID?
struct Data: Identifiable
{
let id = UUID()
var name: String
}
let Data1 = Data(name: "Data 1")
let Data2 = Data(name: "Data 2")
let Data3 = Data(name: "Data 3")
let Data4 = Data(name: "Data 4")
class DataModel: ObservableObject
{
@Published var items: [Data] = [Data1, Data2, Data3, Data4]
}
struct ContentView: View
{
@StateObject var dataModel = DataModel()
var body: some View
{
ForEach(dataModel.items.indices, id: \.self) { index in // ← Here: I want UUID
Text(dataModel.items[index].name)
.font(.title2)
.padding()
}
}
}
答案 0 :(得分:0)
您可以尝试以下方法:
ForEach(dataModel.items.map{ $0.id }, id: \.self) { uuid in // ← Here: I want UUID
答案 1 :(得分:0)
您可以按照How do you use .enumerated() with ForEach in SwiftUI?所述使用zip
ForEach(Array(zip(dataModel.items.indices, dataModel.items)), id: \.1) { index, item in
// index and item are both safe to use here
}