0

我正在尝试使用 @Published var 属性声明 Array。但是,该值永远不会更新(始终为默认值 -> 0)。

我怎样才能做到这一点 ?我究竟做错了什么 ?

非常感谢您的帮助 ;)

祝你今天过得愉快

struct MyCategory: Identifiable, Hashable {
    let id = UUID()
    let name: String
    let amount: Double
}

class MyViewModel: ObservableObject {
    
    @Published var amount1: Double = 0
    @Published var amount2: Double = 0
    @Published var categories = [MyCategory]()
    
    init() {
        self.categories = [
            MyCategory(name: "Test 1", amount: self.amount1),
            MyCategory(name: "Test 2", amount: self.amount2)
        ]
    }

    func updateAmounts(value1: Double, value2: Double) {
        self.amount1 += value1
        self.amount2 += value2
    }
}
    
import SwiftUI

struct MyView: View {
    
    @EnvironmentObject var myViewModel: MyViewModel
    
    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            ForEach(myViewModel.categories, id: \.self) { category in
                HStack() {
                     Text("\(category.name)")
                     Text("\(category.amount)") // Value not refresh! 0
                }
            }
        }
    }
}
4

0 回答 0