2

Clicking UI object NSComboBox incorrectly executes comboBoxSelectionDidChange(...) before it's .stringValue changes instead of after as it's name implies. It does same as .comboBoxSelectionIsChanging.

How can I have comboBoxSelectionDidChange(...) execute after NSComboBox.stringValue actually changes?

class ViewController: NSViewController, NSComboBoxDelegate {
    @IBOutlet weak var comboBox: NSComboBox!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.usernameComboBox.delegate = self
    }

    func comboBoxSelectionDidChange(notification: NSNotification) {
        print(usernameComboBox.stringValue)
        // PRE-selected .stringValue = "ITEM 1"
        // POST-selected .stringValue = "ITEM 2"
        // selecting either item prints PRE-selected
    }
}
dbconfession
  • 1,147
  • 2
  • 23
  • 36

2 Answers2

1

Here is a shorter way:

     func comboBoxSelectionDidChange(notification: NSNotification) {

    guard let stringValue = usernameComboBox.objectValueOfSelectedItem as? String else { return }
    print(stringValue)
}
Eugene Mankovski
  • 1,180
  • 10
  • 16
  • Thanks! Just in case, any other dinosaurs out there like me, using Objective-c, it's NSLog(@"%@", _myComboBox.objectValueOfSelectedItem); – Jens Peter Jun 19 '17 at 18:17
0

Using the code below executes exactly the same as any other NSComboBoxDelegate notification function. Doesn't make sense but it works.

func comboBoxSelectionDidChange(notification: NSNotification) {
    let currentSlection = usernameComboBox.stringValue      
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        while true {
            if self.usernameComboBox.stringValue != currentSlection {
                print(self.usernameComboBox.stringValue)
                break
            }
        }
    })
}
dbconfession
  • 1,147
  • 2
  • 23
  • 36