为什么我的SwiftUI应用程序中没有更新ObservedObject数组? [英] Why is an ObservedObject array not updated in my SwiftUI application?

查看:22
本文介绍了为什么我的SwiftUI应用程序中没有更新ObservedObject数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SwiftUI,试图了解ObservableObject是如何工作的。我有一个Person对象数组。当我将新的Person添加到数组中时,它会重新加载到我的视图中,但是,如果我更改现有Person的值,它不会重新加载到视图中。

//  NamesClass.swift
import Foundation
import SwiftUI
import Combine

class Person: ObservableObject,Identifiable{
    var id: Int
    @Published var name: String
    
    init(id: Int, name: String){
        self.id = id
        self.name = name
    }
}

class People: ObservableObject{
    @Published var people: [Person]
    
    init(){
        self.people = [
            Person(id: 1, name:"Javier"),
            Person(id: 2, name:"Juan"),
            Person(id: 3, name:"Pedro"),
            Person(id: 4, name:"Luis")]
    }
}
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[0].name="Jaime"
                //self.mypeople.people.append(Person(id: 5, name: "John"))
            }) {
                Text("Add/Change name")
            }
        }
    }
}

如果我取消该行的注释以添加新的Person(John),则Jaime的名称会正确显示,但是如果我只更改名称,则不会在视图中显示。

恐怕我做错了什么,或者我可能不了解ObservedObjects如何处理数组。

推荐答案

您可以使用结构而不是类。由于结构的值语义,对Person名称的更改被视为对Person结构本身的更改,并且此更改也是对People数组的更改,因此@Publisher将发送通知并重新计算视图正文。

import Foundation
import SwiftUI
import Combine

struct Person: Identifiable{
    var id: Int
    var name: String

    init(id: Int, name: String){
        self.id = id
        self.name = name
    }

}

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

    init(){
        self.people = [
            Person(id: 1, name:"Javier"),
            Person(id: 2, name:"Juan"),
            Person(id: 3, name:"Pedro"),
            Person(id: 4, name:"Luis")]
    }

}

struct ContentView: View {
    @StateObject var model = Model()

    var body: some View {
        VStack{
            ForEach(model.people){ person in
                Text("(person.name)")
            }
            Button(action: {
                self.mypeople.people[0].name="Jaime"
            }) {
                Text("Add/Change name")
            }
        }
    }
}

或者(不推荐)Person是一个类,所以它是一个引用类型。当它更改时,People数组保持不变,因此主题不会发出任何内容。但是,您可以手动调用它,让它知道:

Button(action: {
    self.mypeople.objectWillChange.send()
    self.mypeople.people[0].name="Jaime"    
}) {
    Text("Add/Change name")
}

这篇关于为什么我的SwiftUI应用程序中没有更新ObservedObject数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆