I have the following View in SwiftUI and what I want is to create a Textfield with the value of the name which is a property of the Model but I have not been able to do it, this is the code:
struct ContentView: View {
@StateObject private var vm = ContentViewModel()
var body: some View {
ScrollView{
ForEach(vm.models){model in
HStack{
Text(model.description)
Text(model.name)
TextField("title", text:model.name)
Spacer()
}
}
}
}
}
extension ContentView{
@MainActor class ContentViewModel:ObservableObject{
@Published var models:[Model]=[]
init() {
self.models = createSomeData()
}
func showData(){
for model in models{
print(model.description)
}
}
func createSomeData()->[Model]{
var local=[Model]()
let model=Model()
model.id=UUID()
model.name="nombre"
model.description="xbox"
local.append(model)
return local
}
}
}
class Model:Identifiable{
var id:UUID=UUID()
var name:String=""
var description:String=""
}
The error that throws me is this: Cannot convert value of type 'String' to expected argument type 'Binding'
When you allow the user to modify data in the interface, in this case a
TextField
, you must take bindings into account . This allows your model data to update automatically and for that the symbol is used$
.The changes in your code are with the variable
vm
that is of typeObservableObject
:We also do a binding of the model:
And finally we add the value in the
TextField
:The modified code:
The result: