一、应用场景
在开发中,我们经常会遇到这样的场景:动态修改model里面的数据,然后根据model实时的刷新视图;
在原来的swift开发中,我们通常都会使用KVO来监听model中属性的变化,然后刷新视图;
在SwiftUI中,通过装饰器(@ObservedObject
,@Published
)可以更快更方便的实现这一点;
二、代码
// model类,必须继承ObservableObject
class ShoppingEntity: ObservableObject {
// @Published用来修饰,需要监听的属性
@Published var count: Int = 0
func increase() {
self.count += 1
}
func decrease() {
if self.count > 0 {
self.count -= 1
}
}
}
// 视图类
struct ShoppingView: View {
// 使用@ObservedObject修饰model对象
@ObservedObject var entity = ShoppingEntity()
var body: some View {
VStack {
Text("商品个数: \(entity.count)").padding()
Button(action: {
self.entity.increase()
}, label: {
Text("增加")
}).padding()
Button(action: {
self.entity.decrease()
}, label: {
Text("减少")
}).padding()
}
}
}
演示
三、对比
- @ObservedObject相对于Swift的KVO,使用起来更加的方便;
网友评论