struct GridCell: View {
@EnvironmentObject var order: Order
class ViewModel: ObservableObject {
let objectWillChange = PassthroughSubject<Void, Never>()
@Published var product : Product {
willSet {
self.objectWillChange.send()
}
}
init(product: Product) {
self.product = product
}
public func increaseAmount() {
self.product.amount += 1
self.objectWillChange.send()
print("\(self.product.amount) / \(self.product.id)")
}
}
func updatePos(){
self.viewModel.increaseAmount()
let itempreis = viewModel.product.preis
order.totalAmount += itempreis
print(order.totalAmount)
}
@ObservedObject var viewModel: ViewModel
var body: some View {
Button(action: {
print("TAPPED")
self.updatePos()
}) {
...
}
}
和GridCell
将是
GridCell(viewModel: GridCell.ViewModel(product: $0))
和Product
是
struct Product : Identifiable, Equatable, Decodable {
var id: String
var name: String
let preis: Double
var amount: Int
}
在我的打印对帐单中,金额没有更新,每按一次该按钮的值就等于1。 我忘记了什么?
答案 0 :(得分:0)
尝试
public func increaseCharacterStrength() {
self.product.amount += 1
}
由于在创建变量Product
时,var viewproduct = self.product
是一个结构,因此您正在创建产品的本地副本,因此viewproduct.amount += 1
只是增加了该局部变量的数量,而不是实际模型。
答案 1 :(得分:0)
我认为您没有正确定义视图模型。由于我没有产品和订单的结构,因此我简化了模型以满足我们的讨论需求。对于下面提供的示例,您可以创建GridCell实例(例如GridCell()),然后点击按钮将数量增加1。另外请注意,可以通过在视图模型中使用@Published属性包装而不是Passthrough来进一步简化操作>
class Order: ObservableObject {
@Published var totalAmount : Int = 0
}
struct Product {
var id = UUID()
var amount: Int = 0
var preis: Int = 0
}
struct GridCell: View {
@EnvironmentObject var order: Order
func updatePos() {
self.viewModel.increaseCharacterStrength()
let itempreis = self.viewModel.product.preis
order.totalAmount += itempreis
//print(order.totalAmount)
print("---- \(self.viewModel.product.amount) / \(self.viewModel.product.id)")
}
@ObservedObject var viewModel = ViewModel(product: Product())
var body: some View {
Button(action: {
print("TAPPED")
self.updatePos()
}) {
Text("Increase order")
}
}
}
class ViewModel: ObservableObject {
let objectWillChange = PassthroughSubject < Void,
Never > ()
var product: Product {
willSet {
self.objectWillChange.send()
}
}
init(product: Product) {
self.product = product
}
public func increaseCharacterStrength() {
self.product.amount += 1
self.objectWillChange.send()
}
}