在 Swift Playground 中访问来自不同页面的变量 [英] Accessing variables from different pages in Swift Playground

查看:35
本文介绍了在 Swift Playground 中访问来自不同页面的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Playground 中有 2 个不同的页面,其中包含一组公共变量,我想在其他页面中使用这些变量(我没有在那里声明任何变量).这可能吗?

I have 2 different pages in my playground with a set of public variables and I want to use those variables in my other page (I have not declared any variables there). Is this possible?

推荐答案

你需要使用@EnvironmentObject 变量.

You need to use @EnvironmentObject variable.

转到 WindowScene 文件.在那里您可以创建对象并将其传递给根视图.像这样:

Go to the WindowScene file. There you can create object and pass it to root View. like this:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    ...
    let device = Device()
    let contentView = ContentView().environmentObject(device)
    ...
}

environmentObject(device) 将设备值变为现金.在 ContentView 中,您可以通过使用 EnvironmentObject 包装器定义变量来访问它

environmentObject(device) puts the device value to cash. In ContentView you can access it by define variable with EnvironmentObject wrapper like this

struct ContentView: View{
    @EnvironmentObject var device: Device
    var body: some View{
         ...
    }
}

请注意,您没有提供任何名称或 ID 来存储值.变量类型就是那个ID.当您更改一个视图中的值时,所有其他视图都会收到通知并自行更新.那是 @EnvironmentObject 包装器.

note that you don't give any name or ID to store the value. Variable type is that ID. When you change the value in one View, all the other views will receive notification and will updates itself. That is @EnvironmentObject wrapper for.

这是您可以在视图之间共享数据的方式.是的,您也可以在其他视图中创建一些视图 init() 并将它们作为结构存储在另一个视图的存储属性中,然后访问结构属性.有时它有助于解决一些性能问题,但通常这不是 SwiftUI 的工作方式.

this is the way you can share data between Views. Yes, you also can create some Views in other Views init() and store them as a struct in stored property of another View and then access struct properties. Sometimes it helps to solve some performance problems, but in general it's not the way the SwiftUI works.

Playground 也可以运行 SwiftUI 代码:

Playground is also able to run SwiftUI code:

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))

这篇关于在 Swift Playground 中访问来自不同页面的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆