SWIFTUI列表想要在列表中切换。无法将类型'MyModel'的值转换为预期的参数类型'Binding '

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

我只是想拥有一个带有文本和切换的记录列表。不知何故我根本无法得到它。我得到了错误:无法将类型'MyModel'的值转换为预期的参数类型'Binding'

如何获得列表中显示的bool值以进行切换并可以更改?

这是我的代码:

struct ContentView: View {

@State var myModels: [MyModel] = [
       MyModel(id: "1", name: "First Model-1-", notify: false),
       MyModel(id: "2", name: "Second Model", notify: true)
   ]

var body: some View {

    List{
        ForEach(myModels, id: \.id){myModel in
            HStack{
            Text(myModel.name)
            Spacer()
            ToggleView(myModel: myModel) //<-- here s the error message: Cannot convert value of type 'MyModel' to expected argument type 'Binding<MyModel>'
        }
        }

}
}

}



struct ToggleView: View {
@Binding var myModel: MyModel // <<

var body: some View {
    HStack {
        Toggle(isOn: $myModel.notify) {
            Text("Done")
        }
        Text(myModel.notify ? "Complete" : "Not complete")

    }
}
}

任何帮助都胜过赞赏!

swift list binding swiftui state
1个回答
0
投票

[您很可能只需要使用两种方式的绑定。因此缺少$:

ToggleView(myModel: $myModel)
© www.soinside.com 2019 - 2024. All rights reserved.