何らかの理由で、Observable のオブジェクトを変数に割り当ててから変更すると、ビューが更新されません。しかし、インデックスで直接アクセスすると、次のようになります。
動作しません:
var people = self.mypeople.people[0]
people.name = 'test'
動作します:
self.mypeople.people[0].name = 'test'
私の推測では参照に関するものですが、よくわかりません:(
コード例:
//: A UIKit based Playground for presenting user interface
import SwiftUI
import PlaygroundSupport
import Combine
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]
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 = People()
var body: some View {
VStack{
ForEach(mypeople.people){ person in
Text("\(person.name)")
}
Button(action: {
var people = self.mypeople.people[0]
// this howver works:
// self.mypeople.people[0].name = 'Test'
people.name="Jaime2"
}) {
Text("Change name")
}
}
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())