选择器中的持久值会更改SwiftUI中的视图

问题描述 投票:3回答:1

我不明白如何在SwiftUI中实现一个简单的选择器,该选择器显示值列表,这些值列表保留所选值在不同视图之间切换。顺便说一下,我能够使用所选的值通过Combine框架更新模型。

这是代码,但是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])
//        }
    }

我认为绑定和didSet将是答案,但我不知道它们如何实现

swift forms picker combine
1个回答
0
投票

提供的代码不可编译/不可测试,因此下面仅显示一种方法(另请参见内联注释)

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)
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.