我希望动态更新Picker的内容。例如,在显示视图后加载选择器列表。下面是示例代码,但无法正常工作。预期的行为是:
观察结果是:
有人知道代码有什么问题吗?
谢谢
struct ContentView: View {
@State var selection = 0
@State var colors: [String] = ["red", "blue", "green"]
var body: some View {
VStack {
Picker(selection: $selection, label: Text("Color")) {
ForEach(self.colors, id: \.self) { color in
Text(color)
}
}
List(colors, id: \.self) { color in
Text(color)
}
Button(action: {
self.colors = ["red", "blue", "green", "yellow"]
}) {
Text("Add Yellow")
}
}
}
}
答案 0 :(得分:0)
以下作品。经过Xcode 11.4 / 13.4的测试
Picker(selection: $selection, label: Text("Color")) {
ForEach(self.colors, id: \.self) { color in
Text(color)
}
}.id(colors) // << here !!