SwiftUI:添加元素时不刷新选择器内容 [英] SwiftUI: Picker content not refreshed when adding Element
问题描述
我在VStack中有一个Picker元素,但是当其内容通过添加新元素而更改时,Picker不会刷新.
I have a Picker Element in a VStack, but when its content changes by adding a new Element, the Picker does not refresh.
隐藏并显示选择器后,新元素可见.
After hiding and showing the Picker, the new Element is visible.
有人不知道如何隐藏选取器的内容来刷新它的内容吗?
Does anybody have any idea how to refresh the content of a Picker, without needing to hide / show it?
您可以通过创建一个新的SwiftUI项目并复制以下代码(而非"ContentView"结构)来重现此内容.
You can reproduce this by creating a new SwiftUI project and copying the following code instead of the "ContentView" struct.
class ContentModel {
@Published var pickerData: [String] = ["1"]
func addPickerData() {
pickerData.append("\(pickerData.count + 1)")
}
}
struct ContentView: View {
let contentModel = ContentModel()
@State private var showPicker = false
@State private var selectedPickerValue = ""
var body: some View {
VStack(spacing: 8) {
Text("Adding a new Element to the Picker does not refresh its content :-(")
Button(action: {
self.contentModel.addPickerData()
}) {
Text("Add Picker Data")
}
Button(action: {
self.showPicker.toggle()
}) {
Text("Show / Hide 2nd Picker")
}
Picker("Select",selection: $selectedPickerValue) {
ForEach(contentModel.pickerData, id: \.self) { data in
Text(data)
}
}
if (showPicker) {
Picker("Select",selection: $selectedPickerValue) {
ForEach(contentModel.pickerData, id: \.self) { data in
Text(data)
}
}
}
Text("Selected Value: \(selectedPickerValue)")
}
}
}
在此先感谢您的帮助!
推荐答案
这是反应性的技巧,当您需要刷新某些内容时,始终使用同一事物的两个副本.
Here is the trick of reactive and always use two copies of same thing when you need to refresh something.
class ContentModel{
@Published var pickerData: [String] = ["1"]
func addPickerData() {
pickerData.append("\(pickerData.count + 1)")
}
}
struct ContentSSView: View {
let contentModel = ContentModel()
@State private var showPicker = false
@State private var selectedPickerValue = ""
var body: some View {
VStack(spacing: 8) {
Text("Adding a new Element to the Picker does not refresh its content :-(")
Button(action: {
self.contentModel.addPickerData()
self.showPicker.toggle()
}) {
Text("Add Picker Data")
}
Button(action: {
self.showPicker.toggle()
}) {
Text("Show / Hide 2nd Picker")
}
if (showPicker) {
Picker("Select",selection: $selectedPickerValue) {
ForEach(contentModel.pickerData, id: \.self) { data in
Text(data)
}
}
}else{
Picker("Select",selection: $selectedPickerValue) {
ForEach(contentModel.pickerData, id: \.self) { data in
Text(data)
}
}
}
Text("Selected Value: \(selectedPickerValue)")
}
}
}
这篇关于SwiftUI:添加元素时不刷新选择器内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!