2

单击 UI 对象会在其更改之前NSComboBox错误地执行,而不是顾名思义之后执行。它与.comboBoxSelectionDidChange(...).stringValue.comboBoxSelectionIsChanging

实际更改后如何comboBoxSelectionDidChange(...)执行?NSComboBox.stringValue

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
    }
}
4

2 回答 2

1

这是一个更短的方法:

     func comboBoxSelectionDidChange(notification: NSNotification) {

    guard let stringValue = usernameComboBox.objectValueOfSelectedItem as? String else { return }
    print(stringValue)
}
于 2016-07-14T14:30:37.010 回答
0

NSComboBoxDelegate使用下面的代码执行与任何其他通知功能完全相同。没有意义,但它有效。

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
            }
        }
    })
}
于 2016-07-13T16:25:43.803 回答