title: SwiftUI macOS Commands (menu bar) and View
body: <p>Hi I am starting to learn SwiftUI and macOS development. I am using the SwiftUI life cycle. How do I call a function from the focused window from the menu bar.</p>
  <p>Besides Apple documentation, I found <a href="https://swiftwithmajid.com/2020/11/24/commands-in-swiftui/" rel="noreferrer">this reference</a> and am able to create menu items using Commands but I have no idea how to call a function from my view.</p>
  <p>For example:</p>
  <p>Suppose this is my App struct:</p>
  <pre><code>import SwiftUI
  
  @main
  struct ExampleApp: App {
      var body: some Scene {
          WindowGroup {
              ContentView()
          }
      }.commands {
          CommandMenu(&quot;First menu&quot;) {
              Button(&quot;Action!&quot;) {
                  // How do I call the views action function?
              }
          }
      }
  }
  </code></pre>
  <p>and this is my View:</p>
  <pre><code>struct ContentView: View {
      public func action() {
          print(&quot;It works&quot;)
      }
      var body: some View {
          Text(&quot;Example&quot;)
      }
  }
  </code></pre>
  <p>I just typed the example code sorry if there are any typos but I hope you can get the idea.</p>