comboBoxSelectionDidChange с несколькими NScombobox - PullRequest
0 голосов
/ 12 сентября 2018

У меня есть приложение с двумя комбинированными окнами в одном представлении, которое загружается из базы данных SQLite.Если пользователь делает выбор в поле со списком 1, я хочу запустить метод для ограничения значений в поле со списком 2.

Я думаю, что мне нужна функция comboBoxSelectionDidChange, но я не знаю, как определить,Функция была вызвана выбором в поле со списком 1 или 2?

Посмотрели параметры функции, но не вижу, как определить, какое поле со списком активировало функцию?

Ответы [ 2 ]

0 голосов
/ 26 сентября 2018

Решение для определения того, какой комбинированный список запустил метод selectionDidChange, работало нормально. Однако я узнал одну вещь: метод запускается перед обновлением .stringValue для нового выбора. Я хотел использовать новый .stringValue в методе selectionDidChange, но обнаружил предыдущий .stringValue.

Я обошел это путем использования indexOfSelectedItem, который обновляется до запуска метода selectionDidChange.

Так мой код стал

// Чтобы можно было ограничить контакты, доступные при выборе компании, используйте функцию 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()

    }
}
0 голосов
/ 12 сентября 2018

notification содержит object, который представляет NSComboBox экземпляр.

Если вы создали 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
    }
}
...