我有一个元素数组,我想使用其中选择一个元素Picker
,我有一个Button
它只是将一个新元素添加到数组中。问题是,当我添加一个元素时,Picker
选择未更新。它不适用于DefaultPickerStyle
,但适用于SegmentedPickerStyle
.
代码:
import SwiftUI
struct ExampleView: View {
@State
var array : Array<Int> = [Int]()
@State
var selection : Int = 0
var body: some View {
VStack {
Picker("", selection: self.$selection) {
ForEach(self.array, id : \.self) { i in
Text(String(i))
}
}
// uncomment, and picker will refresh upon pushing the button
//.pickerStyle(SegmentedPickerStyle())
Button(action: {
self.array.append(self.array.count)
}){
Text("Add me: " + String(self.array.count))
}
}
}
}
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
有没有什么办法解决这一问题?我真的需要更新选择器(以其默认样式)。 Xcode 版本 11.2.1 (11B500)。
正如@e-coms 指出的,有一个类似的问题 https://stackoverflow.com/questions/58660945/swiftui-picker-content-not-refreshed-when-adding-element。找到了一个可接受的解决方法@p-ent https://stackoverflow.com/a/58779351/946635 (github https://github.com/peterent/SwiftUIBug)是重新分配一个唯一的.id(...)
for Picker
每次按下按钮时,都会强制其更新。适应我的问题:
UPD:更好,谢谢@e-coms
import SwiftUI
struct ExampleView: View {
@State
var array : Array<Int> = [0,1,2]
@State
var selection : Int = 0
var body: some View {
VStack {
Picker("", selection: self.$selection) {
ForEach(self.array, id : \.self) { i in
Text(String(i))
}
}
.id(self.array)
Button(action: {
self.array.append(self.array.count)
}){
Text("Add me: " + String(self.array.count))
}
}
}
}
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)