首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从UISceneDelegate更改视图的内容

从UISceneDelegate更改视图的内容
EN

Stack Overflow用户
提问于 2020-04-04 05:39:19
回答 1查看 47关注 0票数 1

我有以下观点。

代码语言:javascript
复制
struct ContentView: View {
@State var data = "Intitial Value"

var body: some View {
    VStack {
        Text(data)
        Button(action: { self.data="Changed value" }) {
            Text("Click Here")
        }
    }
}
}

这段简单的代码运行良好,每当我单击按钮时,它反映在屏幕标签上的数据属性。

现在,我想在收到URL时更改文本标签,但以下代码不起作用。

代码语言:javascript
复制
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let vc = self.window?.rootViewController as? UIHostingController<ContentView> else  {
        return
    }
    vc.rootView.data = "Scene Delegate"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-04 12:33:59

您可以使用通过EnvironmentObject注入的模型视图来实现这一点

代码语言:javascript
复制
class DataViewModel: ObservableObject {
    @Published var data = "Intitial Value"
}

struct ContentView: View {
    @EnvironmentObject var vm: DataViewModel       // < declare
    var body: some View {
        VStack {
            Text(vm.data)                          // < use
            Button(action: { 
                self.vm.data="Changed value"       // < use
            }) {
                Text("Click Here")
            }
        }
     }
}

在SceneDelegate中,将此作为成员

代码语言:javascript
复制
class SceneDelegate {
   var dataVM = DataViewModel()         // << create

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
      ...

       let contentView = ContentView()
                             .environmentObject(dataVM)     // << inject
        window?.rootViewController = UIHostingController(rootView: contentView)
      ...
    }


    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        dataVM.data = "Scene Delegate"     // << modify
    }

    ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61020818

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档