【发布时间】:2019-12-11 17:19:37
【问题描述】:
我有一个带有许多按钮的视图,如果用户点击一个按钮,视图模型需要用增加的值更新当前按钮。
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("...")
}
}
问题是 myInt 每次都只有 1 并且值无法更新。
如何更新值并将其保存在当前模型中,以便视图知道它的增加??!!
struct singleButtonView: View {
@ObservedObject var productVM : ProductVM
func updatePos(){
self.productVM.increaseAmount()
}
}
我用它来称呼它
singleButtonView(productVM: ProductVM(product: product))
【问题讨论】:
-
myInt的原因是什么?直接更新product.amount。做到这一点 - 正确 - 一切都会顺利进行。 -
它是一样的。我将值更改为 Integer 并直接更新,没有任何反应。
-
其他代码可以吗?或者您有什么问题可以看到?
标签: swiftui