SwiftUI 视图模型更新

xyz*_*eee 4 swiftui

我有一个包含许多按钮的视图,如果用户点击按钮,视图模型需要使用增加的值更新当前按钮。

class ProductVM: ObservableObject {
    @Published var product : Product


    init(product: Product) {
        self.product = product
    }


    public func increaseAmount() {
        var myInt = Int(self.product.amount) ?? 0
        myInt += 1
        self.product.amount = String(myInt)

        print(myInt)
        print("...")
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是myInt每次都是 1 并且该值无法更新。

我如何更新该值并将其保存在当前模型中以便视图知道它增加了?

struct singleButtonView: View {
@ObservedObject var productVM : ProductVM




func updatePos(){
    self.productVM.increaseAmount()
  }
 }
Run Code Online (Sandbox Code Playgroud)

我称之为

singleButtonView(productVM: ProductVM(product: product))
Run Code Online (Sandbox Code Playgroud)

krj*_*rjw 11

嵌套ObservableObjects需要手动更新。下面是一个示例:

class Product: ObservableObject, Identifiable, Codable {
    let id: Int
    let name: String
    let prize: Double
    @Published var amount: Int = 0

    enum CodingKeys: String, CodingKey {
        case id
        case name
        case prize
        case amount
    }

    init() {
        self.id = 0
        self.name = "name"
        self.prize = 0
    }

    init(id: Int, name: String, prize: Double) {
        self.id = id
        self.name = name
        self.prize = prize
    }

    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        id = try values.decode(Int.self, forKey: .id)
        name = try values.decode(String.self, forKey: .name)
        prize = try values.decode(Double.self, forKey: .prize)
        amount = try values.decode(Int.self, forKey: .amount)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(id, forKey: .id)
        try container.encode(name, forKey: .name)
        try container.encode(prize, forKey: .prize)
        try container.encode(amount, forKey: .amount)
    }
}


class ProductVM: ObservableObject {
    @Published var product: Product
    var cancelable: AnyCancellable? = nil

    init(product: Product) {
        self.product = product
        self.cancelable = product.objectWillChange.sink(receiveValue: {
            self.objectWillChange.send()
        })
    }

    public func increaseAmount() {
        self.product.amount += 1
    }
}


struct ContentView: View {
    @ObservedObject var productVM = ProductVM(product: Product())

    var body: some View {
        VStack {
            Button(action: {
                self.productVM.increaseAmount()
            }) {
                Text("Add")
            }
            Text("\(self.productVM.product.amount)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助! 制作人员