相关疑难解决方法(0)

为什么我的SwiftUI应用程序中未更新ObservedObject数组?

我正在玩SwitUI,试图了解ObservableObject的工作原理。我有一个Person对象数组。当我将新的Person添加到数组中时,它将重新加载到我的View中。但是,如果我更改现有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")]
    }

}
Run Code Online (Sandbox Code Playgroud)
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, …
Run Code Online (Sandbox Code Playgroud)

swiftui

9
推荐指数
5
解决办法
2594
查看次数

标签 统计

swiftui ×1