swiftswiftuinsmenunsmenuitemswiftui-windowgroup

SwiftUI: How to implement Edit menu in macOS app


I am building a macOS-app using SwiftUI and the new App lifecycle.

All the default macOS menu items (like cut, copy, paste) are already there after starting a new project but they’re greyed out. How can I implement methods for these default menu items?

enter image description here

Edit: I am currently using Xcode 12.2 beta 3 (12B5035g) on macOS Big Sur 11.0.1 Beta (20B5012d). I don’t want to solve this with Storyboards or within AppDelegate but instead with SwiftUI and the new App lifecycle.


Solution

  • Have a look at the commands modifier, the CommandGroup and CommandMenu.

    @main
    struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }.commands {
            // for example
            CommandGroup(replacing: .help) {
                Button(action: {someActionHere()}) {
                    Text("MyApp Help")
                }
            }
            CommandMenu("Edit") {
                // ...
            }
        }
    }
    }