我希望这不是一个愚蠢的问题,但我似乎无法弄清楚。我有一个包含许多条目的数组,我想在选择器中显示一定范围的选项(比如说从数组中的第二项到第五项)。我已经使用ForEach循环完成了此操作,但是我不知道如何指定要运行的循环的确切范围。这是下面的示例代码,可运行但显示整个数组。谢谢您的帮助
import SwiftUI
struct Plans: Identifiable {
var id = UUID()
var plan1: String
var plan2: String
var plan3: String
}
struct ContentView: View {
@State private var picked = ""
let goals = [
Plans(plan1: "A", plan2: "B", plan3: "C"),
Plans(plan1: "D", plan2: "D", plan3: "F"),
Plans(plan1: "F", plan2: "G", plan3: "H"),
Plans(plan1: "I", plan2: "J", plan3: "K"),
Plans(plan1: "L", plan2: "M", plan3: "N"),
Plans(plan1: "o", plan2: "P", plan3: "Q"),
Plans(plan1: "R", plan2: "S", plan3: "T"),
Plans(plan1: "U", plan2: "V", plan3: "W"),
Plans(plan1: "X", plan2: "Y", plan3: "Z")
]
var body: some View {
NavigationView {
Form {
Picker(selection: self.$picked, label: Text("Pick your plan")) {
ForEach(goals, id:\.plan1) { goal in
Text("\(goal.plan1)").tag(goal.plan1)
}
}.id(UUID())
}
}
}
}
答案 0 :(得分:0)
您可以这样做:
ForEach(2..<goals.count, id: \.plan1) { goal in
Text("\(goals[goal].plan1)")
.tag(goals[goal])
}
这是您在swiftui中进行的操作。 在ViewBuilders中不允许进行for-in循环... 例如。因为2 ... 5中的i在swiftui视图中不起作用,但这将:
ForEach(2...5, id: \.self) { goal in
...
}