swiftnscombobox

How can I send action from NSComboBox to a function upon section?


I'm creating a combo box programmatically and I would like to cause the selection from the drop down menu to call a function. I can do it if i'm creating a button using - myButton.action = #selector(some_function(_:)), but it doesn't work with an NSComboBox. here is an example from my code:

func populate_scroller_with_combobox(json_file: Array<Any>, panel: NSView)
{
    let combox = NSComboBox()
    combox.identifier = NSUserInterfaceItemIdentifier(rawValue: "combobox1")
    combox.addItem(withObjectValue: "None")
    combox.addItems(withObjectValues: json_file_content)
    combox.numberOfVisibleItems = 10
    combox.isEditable = false
    combox.action = #selector(some_function(_:))
    combox.selectItem(withObjectValue: "None")
    panel.addSubview(combox)
    combox.frame = CGRect(x:190, y: 30, width: 170, height: 26)
}

@objc func some_function(_ sender: NSButton)
{
    print ( "Combobox value changed." )
}

Solution

  • here is the solution in case that anyone else run into the same issue: add to your ViewController Class 'NSComboBoxDelegate'. to your combobox creation function add 'combox.delegate = self'. add another function called func 'comboBoxSelectionDidChange(_ notification: Notification)' which will be triggered by the selection changes

    class MainViewController: NSViewController, NSComboBoxDelegate
    {    
      override func viewDidLoad()
      {
          super.viewDidLoad()
      }
    
    
      func populate_scroller_with_combobox(json_file: Array<Any>, panel: NSView)
      {
          let combox = NSComboBox()
          combox.identifier = NSUserInterfaceItemIdentifier(rawValue: "combobox1")
          combox.addItem(withObjectValue: "None")
          combox.addItems(withObjectValues: json_file_content)
          combox.numberOfVisibleItems = 10
          combox.isEditable = false
          combox.selectItem(withObjectValue: "None")
          combox.delegate = self
          panel.addSubview(combox)
          combox.frame = CGRect(x:190, y: 30, width: 170, height: 26)
      }
    
      func comboBoxSelectionDidChange(_ notification: Notification)
      {
          print("Combobox value changed.")
      }
    }