我遇到一个问题,即视图不会使用@Observable对象自动更新。
struct Person: Identifiable {
var id: Int
var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
class People: ObservableObject {
@Published var people: [Person]
@Published var kitchens: [Kitchen]
init(){
self.people = [
Person(id: 1, name:"Javier"),
Person(id: 2, name:"Juan"),
Person(id: 3, name:"Pedro")]
}
}
struct ContentView: View {
@ObservedObject var mypeople: People
var body: some View {
VStack{
ForEach(mypeople.people){ person in
Text("\(person.name)")
}
Button(action: {
self.mypeople.people.append(Person(id: 7, name: "New person"))
}) {
Text("Add/Change name")
}
}.onAppear {
self.mypeople.people.append(Person(id: 7, name: "New person"))
}
}
}
所以,我要做的是我必须在onAppear中添加一个新人,而不是在按钮的点击上添加一个新人。简而言之,人员阵列可以说,已经有三个人,而我必须在着陆时添加第四个人。
奇怪的是,如果此视图是根视图,则会添加该人,但是,使用导航链接推入该视图时,此人将不起作用。在第二种情况下,会立即添加和删除新人员,从而使人员数组数保持为三。
但是,只需轻按按钮即可轻松添加新人员。我在这里呆了几个小时。任何帮助将不胜感激!预先感谢!
编辑
我进行了更多调试以找出问题所在。因此,在以下场景中,新用户会自动添加到onAppear中:
1)如果ContentView是应用程序的根视图。 2)如果ContentView是从父视图层次结构中的第一个视图推送的。表示是否有ContentView的子视图。子视图中的导航链接会导致此问题,但是直接从ContentView中导航的链接会成功添加此人。
在创建NavigationLink时,我使用了:
NavigationLink(destination: ContentView()) {
Text("View All")
}
答案 0 :(得分:1)
这是否解决了您在评论中提到的情况:
--address
答案 1 :(得分:0)
好吧,如果我理解正确的话,您想在onAppear中添加一个新人,而不是点击按钮来添加新人。但是如果此视图是根视图,则会添加该人,但是,使用导航链接推入该视图时,该人将不起作用。
所以我准备了一个有效的测试:
struct Person: Identifiable {
var id: Int
var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
struct Kitchen: Identifiable {
var id: Int
var name: String
init(id: Int, name: String){
self.id = id
self.name = name
}
}
class People: ObservableObject {
@Published var people: [Person]
@Published var kitchens: [Kitchen]
init() {
self.people = [ Person(id: 1, name:"Javier"),Person(id: 2, name:"Juan"),Person(id: 3, name:"Pedro")]
self.kitchens = [ Kitchen(id: 1, name:"Kitchen1"),Kitchen(id: 2, name:"Kitchen2"), Kitchen(id: 3, name:"Kitchen3")]
}
}
struct SecondView: View {
@ObservedObject var mypeople: People
@State var newId = Int(arc4random())
var body: some View {
VStack{
ForEach(mypeople.people){ person in
Text("\(person.name)")
}
Button(action: {
self.mypeople.people.append(Person(id: self.newId, name: "New person"))
}) {
Text("Add/Change name")
}
}.onAppear {
print("--------> onAppear")
self.mypeople.people.append(Person(id: self.newId, name: "New person"))
}
}
}
struct ContentView: View {
@ObservedObject var mypeople: People
var body: some View {
NavigationView {
NavigationLink(destination: SecondView(mypeople: mypeople)) {
Text("View All")
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
当然,在SceneDelegate中,您必须声明:
var people = People()
window.rootViewController = UIHostingController(rootView: ContentView(mypeople: people))