具有多个 NScomboboxes 的 comboBoxSelectionDidChange

comboBoxSelectionDidChange with multiple NScomboboxes

我有一个应用程序,在同一视图中有两个组合框,它们都是从 SQLite 数据库加载的。如果用户在组合框 1 中进行选择,我想触发一种方法来限制组合框 2 中的值。

我想我需要 comboBoxSelectionDidChange 函数,但我不知道如何判断该函数是否已被组合框 1 或 2 中的选择触发?

查看了函数参数,但看不出如何判断哪个组合框触发了函数?

notification 包含代表 NSComboBox 实例的 object

如果您已经创建了 NSComboBox 插座

@IBOutlet weak var firstComboBox : NSComboBox!

您可以将实例与 notification object

进行比较
func comboBoxSelectionDidChange(_ notification: Notification) {
    let comboBox = notification.object as! NSComboBox
    if comboBox == firstComboBox {
      // do something with firstComboBox
    } else {
      // it's another comboBox
    }
}

用于确定触发 selectionDidChange 方法的组合框的解决方案运行良好。我确实学到的一件事是,在更新新选择的 .stringValue 之前触发该方法。我想在 selectionDidChange 方法中使用新的 .stringValue,但发现了以前的 .stringValue。

我解决这个问题的方法是使用在触发 selectionDidChange 方法之前更新的 indexOfSelectedItem。

所以我的代码变成了

//为了能够在选择公司时限制可用的联系人,请使用 comboboSelectionDidChange 函数 func comboBoxSelectionDidChange(_通知:通知){

    //Define a constant combobox that takes the notification object and casts it as an NSCombobox
    let combobox = notification.object as! NSComboBox

    //Can now test on the combobox object because we only want to do something if cmbCompany selection changes
    if combobox == cmbCompany {

        //The issue with comboboSelectionDidChange function is that the method is fired before the .stringValue is updated. So using .stringValue wont work as it will use the .stringValue from previous selected item. Therefore use index of       selected item as this is updated before the comboboSelectionDidChange function is fired

        //Define index which is the index of the newly selected item
        let index = cmbCompany.indexOfSelectedItem

        //Because the compIndex index will be the same as the index of the selected item we can get the newly selected company from the compIndex which is used to populate the cmbCombobox
        let company = compIndex[index]

        //Get the idCompany from combobox selection passing in the company from the new selection
        idcom = (delegate as! ViewController).getPrimaryKeyComp(company: company)

        //Call the function to reload the contIndex with only contacts for the company selected
        contIndex = (delegate as!ViewController).getContactForCompany(ic: idcom)

        cmbContact.reloadData()

    }
}