Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

swift - SwiftUI 2: the way to open view in new window

Lets imagine that I have an App

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

@SceneBuilder var body: some Scene {
    WindowGroup {
        BookStoreView( model: storeVM )
    }
    
    #if os(macOS)
    Settings {
        SettingsView(model: config)
    }   
    #endif
}

BookStore have a Grid with a lot of books saved in some DB.

BookView can be initiated by a following way:

BookView(model: bookViewModel)

Target: to open BookView IN A NEW SEPARATED WINDOW(as example by click on the button). How can I do this?


Bonus question: How can I open SettingsView(model: config) from the code?


PS: NavigationLink is not solution for me because I not using the NavigationView.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...:

Info.plist


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...