SwiftUI 2: the way to open view in new window

前端 未结 3 2076
既然无缘
既然无缘 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:34

    I found this answer, which worked for me in terms of being able to open a new window: https://developer.apple.com/forums/thread/651592?answerId=651132022#651132022

    I'm on xcode 12.3, Swift 5.3, running Big Sur.

    The following is an example of how to set things up so a button in the ContentView can be used to open the OtherView window.

    @main
    struct testApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
            WindowGroup("OtherView") {
                OtherView()
            }
            .handlesExternalEvents(matching: Set(arrayLiteral: "*"))
        }
    }
    
    struct ContentView: View {
        @Environment(\.openURL) var openURL
    
        var body: some View {
           Button("Other View") {
               if let url = URL(string: "test://otherview") {
                   openURL(url)
               }
           }
        }
    }
    
    struct OtherView: View {
        var body: some View {
            Text("Other View!")
        }
    }
    
    

    Note: Make sure to follow the URL Scheme instructions included in the linked answer (quoted here for convenience):

    Now in Project->Info->URL Types type in test in the URL Schemes field (and the identifier field too) to register our app with the system.

    I achieved this by editing the Info.plist file and making the additions there, i.e URL types -> URL Schemes...:

提交回复
热议问题