SwiftUI 2:在新窗口中打开视图的方式 [英] SwiftUI 2: the way to open view in new window
问题描述
假设我有一个应用程序
var storeVM = BookStoreViewModel(bla1: bla1, bla2: bla2, bla3: bla3)@SceneBuilder var body:一些场景{窗口组{BookStoreView(型号:storeVM)}#if 操作系统(macOS)设置{设置视图(模型:配置)}#万一}
BookStore 有一个 Grid,其中有很多书保存在某个 DB 中.
BookView 可以通过以下方式启动:
BookView(model: bookViewModel)
目标:在新的独立窗口中打开 BookView(例如单击按钮).我该怎么做?
奖金问题:如何从代码中打开 SettingsView(model: config)
?
PS:NavigationLink
不是我的解决方案,因为我没有使用 NavigationView
.
我找到了这个答案,它在能够打开新窗口方面对我有用:
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
.
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
...:
这篇关于SwiftUI 2:在新窗口中打开视图的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!