我正在尝试使用Combine将数据传递到TextField。通过创建数据模型并使用observableObject,但是当我在textField中使用它时,会显示错误。 无法将类型“字符串”的值转换为预期的参数类型“绑定<字符串>” 。我听不懂。
数据模型
struct People: Identifiable {
var id = UUID()
var name: String
var amount: String
}
let peopleData = [
People(name: "A",amount: ""),
People(name: "B",amount: ""),
People(name: "C",amount: "")
]
ObservableObject
import Combine
class PeopleAllData: ObservableObject{
@Published var peopleStore: [People] = peopleData
}
文本字段
@ObservedObject var store = PeopleAllData()
List{
ForEach(store.peopleStore){ item in
HStack {
TextField("person Name", text: item.name) //Error:- Cannot convert value of type 'String' to expected argument type 'Binding<String>'
Button(action: {}) {
Image(systemName: "minus.circle")
.foregroundColor(.red)
}
}
}
}
.frame(width: screen.width, height: screen.height)
答案 0 :(得分:1)
您需要Binding
才能通过ObservedObject
排列元素,如下所示
ForEach(store.peopleStore.indices, id: \.self){ i in
HStack {
TextField("person Name", text: $store.peopleStore[i].name)