问题
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