0

I am trying to make a year selector, with information that comes from an array, but whenever I select an option the selector always returns automatically to the first position, how could I save the selected year in my $ i.anio?

Thank you enter image description here

//---------------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)") } } } 
4
  • 1
    What is the outer ForEach, do you have a list of pickers in your view? Commented Nov 6, 2021 at 18:16
  • 1
    You are mixing types wildly here, the picker contains Int values but for the data you presented anio is a String but in the struct anio is a Date. Very confusing. Commented Nov 6, 2021 at 18:32
  • @JoakimDanielson I'll change the data types to integer, I'll try again Commented Nov 6, 2021 at 18:44
  • @JoakimDanielson It worked for me changing all the type of data to integer, thanks! Commented Nov 6, 2021 at 19:57

1 Answer 1

1

With your edits, you're very close -- you just need to add "" around the Text input so that it will compile:

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)") } } } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

It worked for me changing all the type of data to integer, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.