SwiftUI属性装饰器(@EnvironmentObject)

一、简介

@EnvironmentObject@ObservedObject类似;
只是model在视图内引入的方式不同

二、代码

// model
class EnvironmentShopEntity: ObservableObject {
    @Published var count: Int = 0
    
    func increase() {
        self.count += 1
    }
    
    func decrease() {
        if self.count > 0 {
            self.count -= 1
        }
    }
}

// 视图
struct EnvironmentShopView: View {
    // 使用@EnvironmentObject装饰model对象
    @EnvironmentObject var entity: EnvironmentShopEntity
    
    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()
        }
    }
}

// 使用视图
let entity = EnvironmentShopEntity()
EnvironmentShopView().environmentObject(entity)

三、实例

实例代码

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容