SwiftUI: How to implement Edit menu in macOS app
Asked Answered
C

1

11

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.

Clywd answered 31/10, 2020 at 17:5 Comment(4)
Did you try to select some text and then select Copy? For me they work out-of-the-box so to say without any extra code. Or do you need copy some custom types?Supermundane
You’re right, it works out of the box if I select the contents of a TextField for example. However I want to be able to run a custom copy function if no specific input field is focused.Clywd
You might want to clarify what version of macOS and Xcode you are using.Supermundane
I just have clarified my original question.Clywd
U
6

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") {
            // ...
        }
    }
}
}
Uranyl answered 31/10, 2020 at 22:49 Comment(2)
I like this article. It explains a bit more. swiftwithmajid.com/2020/11/24/commands-in-swiftuiAvowed
This will create a new menu called Edit, not allow implementing functionality for the existing Edit menu.Banquette

© 2022 - 2025 — McMap. All rights reserved.