SwiftUI 2: the way to open view in new window

前端 未结 3 2093
既然无缘
既然无缘 2021-02-08 09:23

Lets imagine that I have an App

var storeVM = BookStoreViewModel(bla1: bla1, bla2: bla2, bla3: bla3)

@SceneBuilder var body: some Scene {
    WindowGroup {
              


        
3条回答
  •  忘掉有多难
    2021-02-08 09:38

    I have played with code from hillmark's answer and got some better results than his code.

    Even if this code is still not the answer, this may be useful for someone.

    _

    Generlly this code will be useless for you in case you need to work with View based on ViewModel.

    But if you need to work with View only - this is a good solution.

    @main
    struct TestAppApp: App {
        var body: some Scene {
            WindowGroup {
                MainView()
            }
            .handlesExternalEvents(matching: Set(arrayLiteral: Wnd.mainView.rawValue))
            
            WindowGroup {
                HelperView()
            }
            .handlesExternalEvents(matching: Set(arrayLiteral: Wnd.helperView.rawValue))
        }
    }
    
    extension TestAppApp {
        struct MainView: View {
            @Environment(\.openURL) var openURL
            
            var body: some View {
                VStack {
                    Button("Open Main View") {
                        Wnd.mainView.open()
                    }
                    
                    Button("Open Other View") {
                        Wnd.helperView.open()
                    }
                }
                .padding(150)
            }
        }
    
        struct HelperView: View {
            var body: some View {
                HStack {
                    Text("This is ") + Text("Helper View!").bold()
                }
                .padding(150)
            }
        }
    }
    
    
    enum Wnd: String, CaseIterable {
        case mainView   = "MainView"
        case helperView = "OtherView"
        
        func open(){
            if let url = URL(string: "taotao://\(self.rawValue)") {
                print("opening \(self.rawValue)")
                NSWorkspace.shared.open(url)
            }
        }
    }
    

    To work with this code you need to have the following:

提交回复
热议问题