我正在玩 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
使用数组。