How can I move data to other screens with ObservableObject keyword? I save the data on the first page to the variable I created with the keyword Published, but I cannot access this data on the second page.
User Model
import Combine
struct User: Codable, Identifiable {
var id = UUID()
var name: String
var surName: String
}
UserDataStore
import Combine
class UserDataStore: ObservableObject {
@Published var users: [User] = []
}
ContentView
I get information from the user with TextField objects on the contentView screen. After pressing the button, I add it to the array in the UserDataStore. I redirect to the detail page.
struct ContentView: View {
@State var name: String = ""
@State var surName: String = ""
@State var user = User(name: "", surName: "")
@State var show: Bool = false
@ObservedObject var userStore = UserDataStore()
var body: some View {
NavigationView {
VStack(spacing: 50) {
TextField("isim", text: $name)
TextField("soyİsim", text: $surName)
NavigationLink(
destination: DetailView(),
isActive: $show,
label: {
Button(action: {
self.user.name = name
self.user.surName = surName
self.userStore.users.append(user)
self.show = true
}) {
Text("Kaydet")
}
})
}
}
}
}
DetailView
On the detail page, I try to view the recorded information, but I cannot.
struct DetailView: View {
@ObservedObject var user = UserDataStore()
var body: some View {
ForEach(user.users) { item in
Text("\(item.name)")
}
}
}
UserDataStore()initializes a new instance ofUserDataStore, so the details view and the content view have different instances. You either need to directly pass the instace from parent to child, or use something like an EnvironmentObject - New Dev