I have created model and using that model Im modify variable data at multiple places I can modify and enter data succesfully in FirstView. I could able to modify data in the SecondView. In SecondView, Whatever content I type in the textfield it goes away instanly (in short not allowing to enter data and ofc no error shown)
I want to know am i using proper object variable to call model every time
class MainViewModel: ObservableObject {
@Published var name = ""
@Published var age = ""
}
// Using at one place
struct FirstView : View {
@StateObject var mainViewModel = MainViewModel()
var body: some View {
Form {
TextField("", text: self.$MainViewModel.name)
TextField("", text: self.$MainViewModel.age)
}
}
}
// ReUsing same at another place
struct SecondView : View {
@EnvironmentObject var mainViewModel = MainViewModel()
var body: some View {
Form {
TextField("", text: self.$MainViewModel.name)
TextField("", text: self.$MainViewModel.age)
}
}
}
I have tried using @EnvironmentObject using at both view but doesnt work either here
2
Answers
Change
To
Make sure you are injecting in the parent view
@lorem ipsum explain the question perfectly. I am just converting his comments into working code. Please have look. This will make you more clear about your issue about injecting from parent.