how can I update data in TextField that lives in the detail of a NavigationView? I want the data to be updated in the List of the parent View. Here is my code:
class Address: ObservableObject, Identifiable {
let id = UUID()
@Published var name: String
@Published var age: String
init(name: String, age: String) {
self.name = name
self.age = age
}
}
class AddressBook: ObservableObject {
@Published var addresses: [Address]
init(addresses: [Address]) {
self.addresses = addresses
}
}
struct TestData {
static let addressbook = AddressBook(addresses: [
Address(name: "Person1", age: "39"),
Address(name: "Person2", age: "22")
])
}
struct ContentView: View {
@ObservedObject var addressbook = TestData.addressbook
var body: some View {
NavigationView {
List (addressbook.addresses) {address in
NavigationLink(destination: AddressDetail(address: address)) {
Text(address.name)
}
}
.navigationBarTitle("Addressbook")
}
}
}
struct AddressDetail: View {
@ObservedObject var address: Address
var body: some View {
Form {
TextField("name", text: $address.name)
TextField("age", text: $address.age)
}
}
}
This code doesn't work: If I go to the AddressDetail-View, change the TextField values and then go back, the changes don't update in the List-View.
Nico
The problem is that
Addressis a class, so if its published properties changed the reference inaddressesis not changed, butContentViewview observesaddressbookas a container of addresses.Here is demo of possible approach (tested & works with Xcode 12b / iOS 14, also on 11.4 / iOS 13.4)
Alternate: based on
Binding(requires much more changes, so, as for me, less preferable, but worth mention