SwiftUI属性装饰器(@ObservedObject)

一、应用场景

在开发中,我们经常会遇到这样的场景:动态修改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,使用起来更加的方便;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容