原文鏈接:https://github.com/fzhlee/SwiftUI-Guide#-%E7%AC%AC5%E8%8A%82enviromentobject-
本節(jié)課演示如何利用EnvironmentObject,進(jìn)行頁面之間的數(shù)值傳遞励七。使用環(huán)境對象卿啡,您可以在整個程序的任意頁面設(shè)置和讀取該對象捕发。
示例代碼:
import SwiftUI
class UserModel: ObservableObject {
@Published var nickName: String = ""
}
struct ContentView : View {
@EnvironmentObject var model : UserModel //添加一個屬性憋沿,該屬性擁有@EnvironmentObject標(biāo)記赃承,所以當(dāng)需要使用model實例屬性時摘悴,只需要從環(huán)境中獲取該屬性即可
@State var isPresented = false //標(biāo)識是否滑入二級頁面
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