[英]persistent value in a picker changing views in SwiftUI
I don't understand how implementing in SwiftUI a simple picker showing a list of values that retain the selected value switching between different views.我不明白如何在 SwiftUI 中实现一个简单的选择器,该选择器显示一个值列表,该列表保留在不同视图之间切换的选定值。 I'm able to use the selected value to update the Model via Combine framework by the way.
顺便说一句,我可以使用选定的值通过组合框架更新 Model。
here's the code, but the onAppear{}
/ onDisappear{}
doesn't work as expected:这是代码,但
onAppear{}
/ onDisappear{}
没有按预期工作:
struct CompanyView: View {
@ObservedObject var dataManager: DataManager = DataManager.shared
@State var selTipoAzienda = 0
var body: some View {
VStack {
companyPhoto
Text("Company view")
Form {
Picker(selection: $selTipoAzienda, label: Text("Tipo Azienda")) {
ForEach(0 ..< self.dataManager.company.tipoAziendaList.count) {
Text(self.dataManager.company.tipoAziendaList[$0])
}
}
}
Button(action: {self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda]) }) {
Image(systemName: "info.circle.fill")
.font(Font.system(size: 28))
.padding(.horizontal, 16)
}
}
// .onAppear{
// self.selTipoAzienda = self.dataManager.company.tipoAziendaList.firstIndex(of: self.dataManager.company.tipoAzienda) ?? 0
// }
// .onDisappear{
// self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda])
// }
}
I think binding and didSet would be the answer but I don't know how they have to be implemented我认为 binding 和 didSet 将是答案,但我不知道它们必须如何实现
The provided code is not compilable/testable, so below just shows an approach (see also comments inline)提供的代码不可编译/不可测试,因此下面仅显示一种方法(另请参见内联注释)
struct CompanyView: View {
@ObservedObject var dataManager: DataManager = DataManager.shared
@State var selTipoAzienda: Int
init() {
// set up initial value from persistent data manager
_selTipoAzienda = State(initialValue: self.dataManager.company.tipoAziendaList.firstIndex(of: self.dataManager.company.tipoAzienda) ?? 0)
}
var body: some View {
// inline proxy binding to intercept Picker changes
let boundSelTipoAzienda = Binding(get: { self.selTipoAzienda }, set: {
self.selTipoAzienda = $0
// store selected value into data manager
self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[$0])
})
return VStack {
companyPhoto
Text("Company view")
Form {
Picker(selection: boundSelTipoAzienda, label: Text("Tipo Azienda")) {
ForEach(0 ..< self.dataManager.company.tipoAziendaList.count) {
Text(self.dataManager.company.tipoAziendaList[$0])
}
}
}
Button(action: {self.dataManager.cambiaTipoAzienda(tipoAzienda: self.dataManager.company.tipoAziendaList[self.selTipoAzienda]) }) {
Image(systemName: "info.circle.fill")
.font(Font.system(size: 28))
.padding(.horizontal, 16)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.