【问题标题】:How to use Picker with data model如何将 Picker 与数据模型一起使用
【发布时间】:2021-12-20 07:10:21
【问题描述】:

我正在尝试使用来自数组的信息制作年份选择器,但是每当我选择一个选项时,选择器总是自动返回到第一个位置,我如何将所选年份保存在我的 $ 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)")
            }
     }
 }

【问题讨论】:

  • 外层 ForEach 是什么,你的视图中有选择器列表吗?
  • @JoakimDanielson 谢谢!,我更新了我的代码
  • 您在这里疯狂地混合类型,选择器包含 Int 值,但对于您提供的数据 anio 是一个字符串,但在结构 anio 中是一个日期。非常混乱。
  • @JoakimDanielson 我将数据类型更改为整数,我会再试一次
  • @JoakimDanielson 它将所有数据类型更改为整数对我很有用,谢谢!

标签: swiftui picker


【解决方案1】:

通过您的编辑,您非常接近 - 您只需在 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)")
                }
            }
        }
    }
}

【讨论】:

  • 它将所有类型的数据更改为整数对我有用,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-19
  • 2011-01-04
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多