本文介绍了SwiftUI 2:在新窗口中打开视图的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象我有一个应用程序

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具有一个网格,其中许多书籍保存在某个数据库中.

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

BookView可以通过以下方式启动:

BookView can be initiated by a following way:

BookView(model: bookViewModel)

目标:在新的分隔的窗口中打开BookView(例如,通过单击按钮).我该怎么办?

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

奖金问题:如何从代码中打开SettingsView(model: config)?

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

PS:NavigationLink对我来说不是解决方案,因为我没有使用NavigationView.

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

推荐答案

尝试以下类似操作(公正的想法-无法测试)

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)
            }
        }
    }
}

这篇关于SwiftUI 2:在新窗口中打开视图的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 08:07