我有一个应用程序,我需要一个按钮打开两个窗口。在App struct中,我设置了两个窗口组
@main
struct myApp: App {
var body : some Scene {
WindowGroup() {
WelcomeView()
}
WindowGroup("FirstViewGroup") {
FirstView()
}
.handlesExternalEvents(matching: Set(arrayLiteral: "FirstViewGroup"))
WindowGroup("SecondViewGroup") {
SecondView()
}
.handlesExternalEvents(matching: Set(arrayLiteral: "SecondViewGroup"))
}
}
在WelcomeView中,我有以下按钮操作:
Button {
if let firstURL = URL(string: "myApp://FirstViewGroup"), let secondURL = URL(string: "myApp://SecondViewGroup") {
NSWorkspace.shared.open(firstURL)
NSWorkspace.shared.open(secondURL)
}
} label: {
Text("Open Windows")
}
当我在按钮操作中的NSWorkspace.shared.open行中进行注释时,相应的窗口会打开。但是当我有两个连续的NSWorkspace.shared.open调用时,我只得到第一个。思想?我在info.plist中正确设置了URL类型(因为每个窗口单独调用时都会成功打开)
尝试在下一个事件循环中打开第二个URL,如
Button {
if let firstURL = URL(string: "myApp://FirstViewGroup"), let secondURL = URL(string: "myApp://SecondViewGroup") {
NSWorkspace.shared.open(firstURL)
DispatchQueue.main.async {
NSWorkspace.shared.open(secondURL) // << here !!
}
}
} label: {
Text("Open Windows")
}
- 如何使用 SwiftUI 在新窗口中打开第二个场景? ——没有简单的方法可以做到这一点。您需要使用
handlesExternalEvents
. sample :
import SwiftUI
@main
struct TestAppApp: App {
var body: some Scene {
WindowGroup {
MainView()
}
.handlesExternalEvents(matching: Set(arrayLiteral: Wnd.mainView.rawValue))
WindowGroup {
HelperView()
}
.handlesExternalEvents(matching: Set(arrayLiteral: Wnd.helperView.rawValue))
}
}
extension TestAppApp {
struct MainView: View {
@Environment(\.openURL) var openURL
var body: some View {
VStack {
Button("Open Main View") {
Wnd.mainView.open()
}
Button("Open Other View") {
Wnd.helperView.open()
}
}
.padding(150)
}
}
struct HelperView: View {
var body: some View {
HStack {
Text("This is ") + Text("Helper View!").bold()
}
.padding(150)
}
}
}
enum Wnd: String, CaseIterable {
case mainView = "MainView"
case helperView = "OtherView"
func open(){
if let url = URL(string: "taotao://\(self.rawValue)") {
print("opening \(self.rawValue)")
NSWorkspace.shared.open(url)
}
}
}
- 为什么我们需要WindowGroup?不就是一组 View 吗? -- 它告诉 swiftUI 这个 View 可以显示为单独的窗口。
- 一般如何与他们合作? - 只有很多黑客。看起来 SwiftUI 在 MacOS 上真的很糟糕。