When writing a menu-bar application using MenuBarExtra, I want to open a new window when the user taps on a button. I am using .openWindow and data-driven WindowGroup for that purpose.
The issue is that the WindowGroup window also opens when the application starts. I would expect the WindowGroup window not to open when the application starts.
Here's a minimal example that reproduces the issue:
import SwiftUI
@main
struct TestApp: App {
@Environment(\.openWindow) var openWidow
var body: some Scene {
MenuBarExtra(isInserted: .constant(true)) {
Button("Open window") {
openWidow(value: "Hello 👋")
}
} label: {
Text("Test App")
}
WindowGroup("Test", for: String.self) { $str in
if let str {
Text(str)
}
}
}
}
There is a workaround using an application delegate:
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
if let window = NSApplication.shared.windows.first(where: { $0.title == "Test" }) {
window.close()
}
}
}
Am I missing anything?