在 SwiftUI 的 Picker 中添加新元素 [英] Add new Element in Picker in SwiftUI
问题描述
我找不到如何在 SwiftUI 的选择器视图中添加某些元素,在我的示例中,我想在单击按钮时在选择器中添加Z"值.
I can't find how to add some element in a picker view in SwiftUI, in my sample, I want add "Z" value in picker when I click the button.
struct ContentView: View {
@State var values: [String] = ["A", "B", "C"]
@State private var selectedValue = 0
var body: some View {
NavigationView {
Form {
Section {
Picker(selection: $selectedValue, label: Text("Value")) {
ForEach(0 ..< values.count) {
Text(self.values[$0])
}
}
}
Button(action: {
self.values.append("Z")
}, label: {
Text("Add")
})
}.navigationBarTitle("Select a value")
}
}
当我点击按钮时,Z 被添加到values"数组中,但 Picker 没有刷新.
When I click on the button, Z is added to "values" array but Picker is not refreshed.
谢谢:)
推荐答案
您必须通过 id
来识别 SwiftUI 的值,以使其更改可检测:
You must identify values by id
for SwiftUI to make it's changes detectable:
ForEach(0 ..< self.values.count, id: \.self) {
Text(self.values[$0])
}
这样 SwiftIU 就知道它应该在更改时重建选择器.
This way SwiftIU knowns it should rebuild the picker on change.
提示:您可以像这样直接使用元素:
Tip: You can use elements directly like this:
ForEach(values, id: \.self) {
Text($0)
}
不要忘记更改 selectedValue
类型和值以匹配您遵循上述提示的数据源 IF:
Don't forget to change the selectedValue
type and value to match with the dataSource IF you followed the tip above:
@State private var selectedValue = "A"
这篇关于在 SwiftUI 的 Picker 中添加新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!