原文链接:https://github.com/fzhlee/SwiftUI-Guide#-%E7%AC%AC5%E8%8A%82enviromentobject-
本节课演示如何利用EnvironmentObject,进行页面之间的数值传递。使用环境对象,您可以在整个程序的任意页面设置和读取该对象。
示例代码:
import SwiftUI
class UserModel: ObservableObject {
@Published var nickName: String = ""
}
struct ContentView : View {
@EnvironmentObject var model : UserModel //添加一个属性,该属性拥有@EnvironmentObject标记,所以当需要使用model实例属性时,只需要从环境中获取该属性即可
@State var isPresented = false //标识是否滑入二级页面
var body: some View {
NavigationView {
VStack{
TextField("Your nickname", text: $model.nickName)
.padding()
NavigationLink(destination: DetailView()) {
Text("Show Detail")
}
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
let model = UserModel()
model.nickName = "Super man"
return ContentView().environmentObject(model)
}
}
#endif
网友评论