首页 > 解决方案 > 有没有办法只更新 EnvironmentObject 中的某些元素

问题描述

例如,我希望每个列表元素独立于其他数据。

这样,更改一个名称不会影响另一个。但如果从另一个视图更改它们,我也希望更新列表。

struct ContentView: View {
    var listView = People()
    let tempPerson = Person()

    var body: some View {
        VStack {
            Button(action: {
                self.listView.people.append(self.tempPerson)
            }){
                Text("Add person")
            }
            ListView().environmentObject(listView)
        }.onAppear{self.listView.people.append(self.tempPerson)}
    }
}

struct ListView : View {
    @EnvironmentObject var listView : People

    var body: some View{
        List(listView.people.indices, id: \.self) { index in
            TextField("StringProtocol", text: self.$listView.people[index].name)
        }
    }
}
class Person {
    var name = "abc"
}

class People : ObservableObject {
    @Published var people : [Person]

    init() {
        self.people = []
    }
}

标签: swiftswiftui

解决方案


Person是一类。这意味着如果您创建:

let tempPerson = Person()

然后在您内部的每个地方,您ContentView都将引用同一个Person实例 - 您将在按钮操作中附加同一个人:

Button(action: {
    self.listView.people.append(self.tempPerson)
}) {
    Text("Add person")
}

我建议您将您的更改Personstruct而不是class

struct Person {
    var name = "abc"
}

复制结构时,每次追加新项目时:

self.listView.people.append(self.tempPerson)

它将是原件的副本tempPerson,您将能够独立更改您的项目。

你可以在这里阅读更多:结构和类


推荐阅读