How to get control from a combo box selection?

Using a combo box after a selection I want to get control to take some actions based on the selection after press tab or return in the field. I have tried a few controls like the one below:

Code Block
// textShouldEndEditing
    func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
        print(#function,control.tag)

But the above control only gets control if the field is edited. I want control once tab, an item selected or return is pressed while on the filed. How is this done?

Accepted Reply

You can create an IBAction

Code Block
@IBAction func comboAction(_ sender: NSComboBox) {
print("Combo selected", sender.selectedTag(), sender.selectedCell()?.title)
}

And connect it to the NSComboBox sentAction in IB / Connections Inspector

You can also:
  • declare that the class conforms to NSComboBoxDelegate

  • create an IBOutlet for the comboBox (not the BoxCell)

Code Block
@IBOutlet weak var itemComboBox: NSComboBox! 
  • set its delegate in viewDidLoad

Code Block
        itemComboBox.delegate = self

Then call any of the delegate func:
Code Block
func comboBoxSelectionIsChanging(_ notification: Notification) {
print("Selection is changing", notification)
}
func comboBoxSelectionDidChange(_ notification: Notification) {
print("Selection has changed", notification)
}



Replies

You can create an IBAction

Code Block
@IBAction func comboAction(_ sender: NSComboBox) {
print("Combo selected", sender.selectedTag(), sender.selectedCell()?.title)
}

And connect it to the NSComboBox sentAction in IB / Connections Inspector

You can also:
  • declare that the class conforms to NSComboBoxDelegate

  • create an IBOutlet for the comboBox (not the BoxCell)

Code Block
@IBOutlet weak var itemComboBox: NSComboBox! 
  • set its delegate in viewDidLoad

Code Block
        itemComboBox.delegate = self

Then call any of the delegate func:
Code Block
func comboBoxSelectionIsChanging(_ notification: Notification) {
print("Selection is changing", notification)
}
func comboBoxSelectionDidChange(_ notification: Notification) {
print("Selection has changed", notification)
}



Thanks Claude, I used the @IBAction because I needed the contents of the comboBox and I had tried the delegate before and could not see a way to get contents of comboBox.