swiftui - 如何将 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)")
}
}
}
解决方案
通过您的编辑,您已经非常接近了——您只需要""
在输入周围添加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)")
}
}
}
}
}
推荐阅读
- python - 无法将 jupytor 笔记本上传到本地主机
- xml - 用于重新启动计算机的 PowerShell/XML toast 通知不起作用。我可以使用特定的 XML 命令吗?
- python - 如何在python中删除数据框中单词的完全匹配?
- vue.js - vue cli 项目不会运行 - 'babel-code-frame'
- python - pandas Groupby求和和连接
- r - R中社区检测算法的不同模块化分数
- swift - 如果 Preview Content 文件夹中有 SwiftUI Previews 的代码,为什么存档会失败?
- nginx - Magento 2 与 Varnish 和 Nginx 作为 SSL 终止 - 后端服务器正在服务
- scikit-learn - TypeError: float() 参数必须是字符串或数字,而不是我使用 model.fit(X_train,y_train) 时的“方法”
- reactjs - 元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“typeof”