从UISceneDelegate更改视图的内容

时间:2020-04-03 21:39:18

标签: swiftui

我有以下看法。

struct ContentView: View {
@State var data = "Intitial Value"

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

只要我单击按钮,它将反映在屏幕标签上的data属性,此简单代码就可以正常工作。

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用通过EnvironmentObject注入的模型视图来完成此操作

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中将其作为成员

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
    }

    ...