SwiftUI属性装饰器(@EnvironmentObject)
2021-06-10 本文已影响0人
fanren
一、简介
@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)