最佳答案
我正在玩 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
(约翰)行,Jaime 的名称显示正确,但如果我只是更改名称,这不会显示在视图中。
我担心我做错了什么,或者我不知道 ObservedObjects
是如何处理数组的。