how to use menu compoennt

Asked on 08/07/2024

1 search

To use the menu component in your app, you can leverage the new SwiftUI integrations with AppKit. Here's a step-by-step guide based on the information from the WWDC session "What’s new in AppKit":

  1. Create a SwiftUI Menu:

    • Define your menu using a SwiftUI view. You can use various SwiftUI views to describe the data relationship, such as toggles, pickers, and buttons.
    • Example:
      import SwiftUI
      
      struct MyMenu: View {
          var body: some View {
              Menu {
                  Button("Action 1", action: { /* perform action 1 */ })
                  Button("Action 2", action: { /* perform action 2 */ })
                  Toggle("Toggle Option", isOn: $toggleState)
                  Picker("Picker Option", selection: $selectedOption) {
                      Text("Option 1").tag(1)
                      Text("Option 2").tag(2)
                  }
              } label: {
                  Text("Menu")
              }
          }
      }
      
  2. Initialize an NSHostingMenu:

    • Use NSHostingMenu to initialize the menu with the SwiftUI view you created.
    • Example:
      import AppKit
      import SwiftUI
      
      let myMenu = NSHostingMenu(rootView: MyMenu())
      
  3. Use the Menu in AppKit Contexts:

    • You can use this menu in any AppKit context that accepts an NSMenu, such as the new NSPopupButton initializer with a pull-down menu parameter.
    • Example:
      let popupButton = NSPopUpButton()
      popupButton.menu = myMenu
      

For more detailed information, you can refer to the session "What’s new in AppKit" at timestamp 06:18.