How do you connect SwiftUI app commands to functions within other views?

Viewed 262

The new SwiftUI app declaration introduced at WWDC20 allows the implementation of app commands which appear in the menu bar. How should these be connected to their respective function in subviews?

Sample Code

struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .commands {
            CommandGroup(after: CommandGroupPlacement.newItem) {
                Button("Do something", action: {
                    // Call the function in SubView
                })
            }
        }
    }
}

struct SubView: View {
    var body: some View { ... }
    
    func doSomething() {
        
    }
}

Ideas which I had thought of include:

  • NotificationCenter
  • Combine publishers
  • EnvironmentObjects

What is the best practice to achieve this?
Thank you, any help is greatly appreciated.

0 Answers
Related