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)