Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 有没有办法只更新EnvironmentObject中的某些元素_Swift_Swiftui - Fatal编程技术网

Swift 有没有办法只更新EnvironmentObject中的某些元素

Swift 有没有办法只更新EnvironmentObject中的某些元素,swift,swiftui,Swift,Swiftui,例如,我希望每个列表元素独立于其他元素的数据 这样,更改其中一个的名称不会影响另一个。但如果从另一个视图更改列表,我也希望该列表得到更新 struct ContentView: View { var listView = People() let tempPerson = Person() var body: some View { VStack { Button(action: { self.li

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

这样,更改其中一个的名称不会影响另一个。但如果从另一个视图更改列表,我也希望该列表得到更新

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)
        }
    }
}

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

let tempPerson = Person()
然后在
ContentView
中的每个地方,您都会引用相同的
Person
实例,并在按钮操作中附加相同的Person:

Button(action: {
    self.listView.people.append(self.tempPerson)
}) {
    Text("Add person")
}
我建议您将
Person
更改为结构而不是类:

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

self.listView.people.append(self.tempPerson)
它将是原始
tempPerson
的副本,您可以独立更改您的项目

您可以在此处阅读更多内容:

struct Person {
    var name = "abc"
}
self.listView.people.append(self.tempPerson)