我在操场上有2个不同的页面,其中包含一组公共变量,我想在其他页面中使用这些变量(我在那里没有声明任何变量)。这可能吗?
您需要使用@EnvironmentObject变量。
转到WindowScene文件。在那里,您可以创建对象并将其传递到根视图。像这样:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
...
let device = Device()
let contentView = ContentView().environmentObject(device)
...
}
environmentObject(device)
将设备价值转换为现金。在ContentView中,您可以通过使用EnvironmentObject包装器定义变量来访问它,如下所示
struct ContentView: View{
@EnvironmentObject var device: Device
var body: some View{
...
}
}
请注意,您没有提供任何名称或ID来存储值。变量类型是该ID。当您在一个视图中更改值时,所有其他视图将收到通知并进行自我更新。那是@EnvironmentObject
包装器。
这是在视图之间共享数据的方式。是的,您还可以在其他视图init()
中创建一些视图,并将它们作为结构存储在另一个视图的存储属性中,然后访问结构属性。有时它有助于解决一些性能问题,但总的来说,这不是SwiftUI的工作方式。
游乐场还能够运行SwiftUI代码:
import SwiftUI
import PlaygroundSupport
class Counter: ObservableObject{
@Published var currentValue = 0
}
struct ContentView: View {
@EnvironmentObject var counter: Counter
var body: some View {
VStack{
Text("count is \(counter.currentValue)")
Text("tap me")
.onTapGesture {
self.counter.currentValue += 1
}
}
}
}
var counter = Counter()
PlaygroundPage.current.setLiveView(ContentView().environmentObject(counter))