I'm trying to create a simple NavigationView showing a list of users and be able to edit them in a child view, while using ObservableObject. The only way I could the ObservedObjects to automatically update between the 2 views is to pass the entire users collection from the parent to the child View so that I could call self.users.objectWillChange.send().
This seems inefficient. Is there a better way to do this?
Model Classes
class User: Identifiable, ObservableObject
{
let id = UUID()
@Published var name: String
init(name: String) { self.name = name }
}
class Users: ObservableObject
{
@Published var users: [User]
init() {
self.users = [
User(name: "John Doe"),
User(name: "Jane Doe"),
]
}
}
Views
struct TestNavigationView: View {
@ObservedObject var users = Users()
var body: some View {
NavigationView {
List(self.users.users) { user in
NavigationLink(destination:
UserDetail(user: user,
users: self.users)
) {
Text(user.name)
}
}
}.navigationBarTitle("Users")
}
}
struct UserDetail: View {
@ObservedObject var user: User
@ObservedObject var users: Users
var body: some View {
VStack {
TextField("Enter Name", text: $user.name)
Button(action: {
self.users.objectWillChange.send()
}, label: { Text("Save") })
}
}
}