SwiftUI 2: the way to open view in new window

痴心易碎 提交于 2020-08-07 05:05:11

问题


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.


回答1:


Try something like the following (just idea - cannot test)

class BookViewModel: ObservableObject {} 

class AppState: ObservableObject {
    @Published var selectedBook: BookViewModel?
}

@main
struct SwiftUI2_MacApp: App {
    @StateObject var appState = AppState()

    @SceneBuilder 
    var body: some Scene {
        WindowGroup {         // main scene
            ContentView()
              .environmentObject(appState)   // inject to update
                                             // selected book
        }

        WindowGroup("Book Viewer") { // other scene
            if appState.selectedBook != nil {
                Book(model: appState.selectedBook)
            }
        }
    }
}


来源:https://stackoverflow.com/questions/62915324/swiftui-2-the-way-to-open-view-in-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!