【发布时间】:2019-12-18 22:43:36
【问题描述】:
我正在使用 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 是如何处理数组的。
【问题讨论】:
标签: swiftui