Search code examples
swiftcocoaswift3nscombobox

How to implement the data source for multiple combo boxes in the same view controller


I have 2 combo boxes that use the same dictionary as the data source. in the first combo box the keys will be displayed and in the second one the values will be displayed.

First I need a bit of help with implementing the data source delegate methods; please see code listing below. the relevant boxes are floorsBox and roomsBox. Ignore the other 2 as they will be populated from a local variable or from the interface. Also, lets say that for the first floor [key = 0] i have 3 rooms [value = 3], how do I take the value of 3 and make it into 3 items inside the roomsBox; So that every time the floor changes the box for the rooms has the corresponding number of items (if that makes sense). I really do appreciate your help and I thank you.

class RoomAndAlarmTypesVC: NSViewController, NSComboBoxDelegate, NSComboBoxDataSource {

//MARK: - Properties

private var floorsAndRooms = [String: String]()

@IBOutlet private weak var floorsBox: NSComboBox!

@IBOutlet private weak var roomsBox: NSComboBox!

@IBOutlet private weak var roomType: NSComboBox!

@IBOutlet private weak var alarmType: NSComboBox!

//MARK: - Actions

override func viewDidLoad() {
    super.viewDidLoad()
    floorsAndRooms = representedObject as! [String : String]
    floorsBox.usesDataSource = true
    roomsBox.usesDataSource = true
    roomType.usesDataSource = true
    alarmType.usesDataSource = true

    floorsBox.delegate = self
    roomsBox.delegate = self
    roomType.delegate = self
    alarmType.delegate = self

    floorsBox.dataSource = self
    roomsBox.dataSource = self
    roomType.dataSource = self
    alarmType.dataSource = self
}
@IBAction private func setTheSystem(_ sender: NSButton) {

}

func numberOfItems(in comboBox: NSComboBox) -> Int {
    what do i do here?
}

func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
    same here?
}

}


Solution

  • Use a switch statement based on the sender (your comboBox parameter)

    for example:

    switch comboBox
    {
        case floorsBox :  return // the data for floors 
        case roomsBox :  return // the data for rooms 
        ...
    }