Why an ObservedObject array is not updated in my SwiftUI application?

前端 未结 4 1467
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 00:53

I\'m playing with SwitUI, trying to understand how ObservableObject works. I have an array of Person objects. When I add a new Person into the array, it is reloaded in my Vi

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 01:32

    I think there is a more elegant solution to this problem. Instead of trying to propagate the objectWillChange message up the model hierarchy, you can create a custom view for the list rows so each item is an @ObservedObject:

    struct PersonRow: View {
        @ObservedObject var person: Person
    
        var body: some View {
            Text(person.name)
        }
    }
    
    struct ContentView: View {
        @ObservedObject var mypeople: People
    
        var body: some View {
            VStack{
                ForEach(mypeople.people){ person in
                    PersonRow(person: person)
                }
                Button(action: {
                    self.mypeople.people[0].name="Jaime"
                    //self.mypeople.people.append(Person(id: 5, name: "John"))
                }) {
                    Text("Add/Change name")
                }
            }
        }
    }
    

    In general, creating a custom view for the items in a List/ForEach allows each item in the collection to be monitored for changes.

提交回复
热议问题