首页 > 解决方案 > 如何将 Picker 与数据模型一起使用

问题描述

我正在尝试使用来自数组的信息制作年份选择器,但是每当我选择一个选项时,选择器总是自动返回到第一个位置,我如何将所选年份保存在我的 $ i.anio 中?

谢谢 在此处输入图像描述

//---------------MODEL-----------------
struct SysNoAntpatologicosModel {
    var anio: Int
    var descripcion: String
    var idantnopat: Int
    var nombre: String
    var presente: Bool
}
//-------------ARRAY----------------
[{
    anio = 2001;
    descripcion = "test1";
    idantnopat = 38;
    nombre = Accidente;
    presente = 0;
},
{
    anio = 2002;
    descripcion = "test2";
    idantnopat = 42;
    nombre = Inmunizacion;
    presente = 0;
}
]

@State var dataSys : [SysNoAntpatologicosModel] = []

 ForEach($dataSys, id: \.idantnopat) { $i in
     HStack{
            Picker("", selection: $i.anio) {
                   ForEach(2000...2021, id: \.self) {
                           Text($0)
                   }
            }
            .pickerStyle(InlinePickerStyle())
            .onChange(of: i.anio) { tag in
               print("year: \(tag)")
            }
     }
 }

标签: swiftuipicker

解决方案


通过您的编辑,您已经非常接近了——您只需要""在输入周围添加Text即可编译:

struct SysNoAntpatologicosModel {
    var anio: Int
    var descripcion: String
    var idantnopat: Int
    var nombre: String
    var presente: Bool
}

struct ContentView : View {
    @State var dataSys : [SysNoAntpatologicosModel] =
        [.init(anio: 2001, descripcion: "test1", idantnopat: 38, nombre: "Accidente", presente: false),
         .init(anio: 2002, descripcion: "test2", idantnopat: 42, nombre: "Inmunizacion", presente: false),
        ]
    
    
    var body: some View {
        ForEach($dataSys, id: \.idantnopat) { $i in
            HStack{
                Picker("", selection: $i.anio) {
                    ForEach(2000...2021, id: \.self) {
                        Text("\($0)") //<-- Here
                    }
                }
                .pickerStyle(InlinePickerStyle())
                .onChange(of: i.anio) { tag in
                    print("year: \(tag)")
                }
            }
        }
    }
}

推荐阅读