我有一个从 API 获取数据的视图,我想做的是根据从最高到最低的点对行进行排名(我现在可以这样做)但是问题是我想显示行号,如 #1 ,#2 等等 .. 正如您从下面的红色背景图像中看到的那样,它对两行都说 1 2 而不是第一行说 1 和第二行说 2 。这是我下面的代码。我已经发表了 // issue is here 的评论,这是问题所在。如您所见,我已经在使用传入 api data 的 forEach 。有没有一种方法可以使用 foreach ForEach(result) 并从 1...n 对行进行编号,并且仍然能够像我一样检索数据。我见过有人这样做的例子,但通常是针对简单的字符串数组。任何建议都会很棒。
ScrollView(showsIndicators: false) {
LazyVStack {
let result = model.sorted {
$0.points! > $1.points!
}
ForEach(result) { value in
VStack(alignment: .leading) {
Spacer()
HStack {
ForEach(0..<result.count) { i in
Text("\(i + 1)")
.frame(width: 20, height: 20, alignment: .center)
.foregroundColor(.white)
.background(Color.red)
} // issue is here
Text(value.initials!)
.fontWeight(.bold)
.frame(width: 50, height: 50, alignment: .center)
.foregroundColor(Color(SystemColorPicked(picked: value.color)))
.padding()
.overlay(
Circle()
.stroke(Color.white, lineWidth: 4)
.padding(6)
)
VStack(alignment: .leading, spacing: 1) {
Text("\(value.fullname ?? "NA")")
.foregroundColor(.white)
.fontWeight(.bold)
Text("\(value.points ?? 0) | points")
.foregroundColor(.white)
}
}
}
}
}
}
答案 0 :(得分:1)
问题是您在 other ForEach
的项目中运行了一个 ForEach
。第二个是每次都显示“1 2”的,因为它每次都遍历所有结果。
我没有您的所有代码,因此我不确定 results
是什么类型,但这里有一个示例,您可以根据自己的用例进行调整。请记住,您将对外部(即第一个)ForEach
循环执行此操作:
struct ContentView : View {
@State private var results = ["Test1","Test2","Test3"]
var body: some View {
VStack {
ForEach(Array(results.enumerated()), id: \.1) { (index, value) in
Text("\(index + 1) \(value)")
}
}
}
}
发生了什么:
对于 ForEach
,我正在使用 results
(或在您的代码中使用 result
).enumerated
- 这提供了一个索引/项目对。我将其包装在 Array()
中,否则 ForEach
将不想采用该特定类型的序列。
ForEach 必须有一个 id
-- 这里我只使用 String
本身。对于您的目的,它可能会有所不同。 .1
指的是元组的第二项(即项,不是索引)
在 ForEach
闭包中,您现在得到 index
和 value