swift - 有没有办法只更新 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 = []
}
}
解决方案
Person
是一类。这意味着如果您创建:
let tempPerson = Person()
然后在您内部的每个地方,您ContentView
都将引用同一个Person
实例 - 您将在按钮操作中附加同一个人:
Button(action: {
self.listView.people.append(self.tempPerson)
}) {
Text("Add person")
}
我建议您将您的更改Person
为struct而不是class:
struct Person {
var name = "abc"
}
复制结构时,每次追加新项目时:
self.listView.people.append(self.tempPerson)
它将是原件的副本tempPerson
,您将能够独立更改您的项目。
你可以在这里阅读更多:结构和类
推荐阅读
- g++ - 如何修复“'g++' 不是内部或外部命令、可运行程序或批处理文件。”
- reactjs - React / Memo:用 React.memo 包装所有功能组件
- python - 计算简单的移动平均熊猫循环
- java - 为什么这个字符串连接算法需要这么多步骤?
- c# - 如何在参数中传递函数列表?(UnityAction[])
- r - 尽管安装成功,但无法从命令行打开 rstudio
- assembly - 逻辑左移
- django - 应用程序配置 - 模块,未正确配置?帮助 Divio
- php - laravel 多对多关系新
- spring-boot - Spring 应用程序上下文未在 Docker 容器中初始化