swiftui - SwiftUI ViewModel 更新
问题描述
我有一个带有许多按钮的视图,如果用户点击一个按钮,则 Viewmodel 需要使用增加的值更新当前按钮。
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))
解决方案
嵌套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)")
}
}
}
我希望这有帮助! 学分
推荐阅读
- android - Android Firebase Query 在不同的键中查找多个值
- unit-testing - 模拟父级内部依赖
- json - 使用 jq 合并两个文件
- java - 如何运行特定的测试类基础系统属性“环境”?
- node.js - 如何读取我从服务器获取的图像作为缓冲区?
- python - 如何修复模板语法错误?
- python - 我的 python 代码在单人学习应用程序上运行正常,但在电脑上运行不正常
- ios - 在 macOS 上解码后,在 iOS 上编码为 Data 的 Int 数为零
- python - 当我不保存时,Python 中的 IDLE 编辑器不会运行我的代码
- azure-eventhub - 为什么捕获的 SystemProperties 和 Properites 的 azure eventthub 信息为空?