Skip to content

Instantly share code, notes, and snippets.

@jaywardell
Created August 16, 2023 12:43
Show Gist options
  • Save jaywardell/e3e3d292d9f339452ccc552bba4c45dd to your computer and use it in GitHub Desktop.
Save jaywardell/e3e3d292d9f339452ccc552bba4c45dd to your computer and use it in GitHub Desktop.
//
// MenuCommandTestsApp.swift
// MenuCommandTests
//
// Created by Joseph Wardell on 8/16/23.
//
import SwiftUI
let SecondWindowIdentifier = "SecondWindowIdentifier"
@main
struct MenuCommandTestsApp: App {
@Environment (\.openWindow) var openWindow
var body: some Scene {
WindowGroup {
VStack(alignment: .leading) {
Text("On iOS, the openWindow envirionment instance that is passed to your command groups is not the same one that is passed to your app (as of iOS 16)")
.padding()
Text("In fact, the one passed to your command groups is apparently not aware of the SwiftUI lifecycle at all.")
.padding()
Text("One way to get around this is to pass the openWindow instance from your app down to your commands. This is ugly, but it works on both iOS and macOS.")
.padding()
Button("You can use the same openWindow instance from here…") {
openWindow(id: SecondWindowIdentifier)
}
.padding()
}
}
.commands {
NewCommands(openWindowAction: openWindow)
}
WindowGroup("New Window opened using openWindow", id: SecondWindowIdentifier) {
VStack {
Text("This way, the window can be opened from either a button OR a menu item on either iOS or macOS")
Text("Yes, it's an ugly hack. More elegant suggestions are welcome.")
}
}
}
}
struct NewCommands: Commands {
let openWindowAction: OpenWindowAction
var body: some Commands {
CommandGroup (replacing: .newItem) {
OpenNewWindowButton(openWindow: openWindowAction)
.keyboardShortcut ("n", modifiers: [.command, .shift])
}
}
}
struct OpenNewWindowButton: View {
let openWindow: OpenWindowAction
@Environment (\.supportsMultipleWindows) private var canOpen
var body: some View {
if canOpen {
Button {
openWindow(id: SecondWindowIdentifier)
} label: {
Label ("…that you use from here", systemImage: "rectangle.badge.plus")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment