Internet上的所有示例均显示以下用于实现选择器的代码类型:
struct MyView: View
{
var colours = ["Red", "Green", "Blue"]
@State private var myColourIndex = 1
@State private var myColour = "Green"
var body: some View
{
VStack
{
Picker(selection: $myColourIndex, label: Text("Choose a colour"))
{
ForEach(0 ..< colours.count)
{
Text(self.colours[$0])
}
}
}
}
}
这可能非常明显,但是我的问题是如何根据存储在myColour中的字符串值而不是索引来设置节?
答案 0 :(得分:2)
实际上几乎是相同的(经过测试并可以在Xcode 11.2 / iOS 13.2上使用):
struct MyView: View
{
var colours = ["Red", "Green", "Blue"]
@State private var myColourIndex = 1
@State private var myColour = "Green"
var body: some View {
VStack {
Picker("Choose a colour", selection: $myColour) {
ForEach(colours, id: \.self) { colour in
Text(colour)
}
}
}
}
}