how do you select an item in a NSMenu

Generated on 7/31/2024

1 search

To select an item in an NSMenu, you can use the NSMenu API provided by AppKit. Here is a basic example of how you can create an NSMenu, add items to it, and select an item programmatically:

import Cocoa

// Create a new NSMenu
let menu = NSMenu(title: "Example Menu")

// Add items to the menu
menu.addItem(withTitle: "Item 1", action: #selector(menuItemSelected(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Item 2", action: #selector(menuItemSelected(_:)), keyEquivalent: "")
menu.addItem(withTitle: "Item 3", action: #selector(menuItemSelected(_:)), keyEquivalent: "")

// Function to handle menu item selection
@objc func menuItemSelected(_ sender: NSMenuItem) {
    print("Selected item: \(sender.title)")
}

// Select an item programmatically
if let itemToSelect = menu.item(withTitle: "Item 2") {
    menu.performActionForItem(at: menu.index(of: itemToSelect))
}

In this example:

  • An NSMenu is created and items are added to it.
  • Each item has an associated action (menuItemSelected(_:)) that is called when the item is selected.
  • The performActionForItem(at:) method is used to programmatically select an item by its index.

For more detailed information on NSMenu and its capabilities, you can refer to the What’s new in AppKit session from WWDC 2024.