Hi,
I'm new to Swift and have met an issue populating a combobox with a dataset pulled from a PostGreSQL database. I can connect to the database just fine, but I can't figure out how to set the datasource on the dropdown, or otherwise populate the items in the combobox. I am atempting to connect to the database and populate the dropdown in AppDelegate while my UI is in a storyboard. I'm guessing I'm somehow refrencing the combobox incorrectly?
If I try to add items to the dropdown individually, the code runs fine but the combobox doesn't populate. If I attempt to set the datasource to a dictionary filled with the Keys and Values I get "Cannot assign value of type '[String : Int]' to type 'NSComboBoxDataSource?'."
I know in Windows Forms I can set a name and value for each item in my comboboxes. Is this possible here too?
Thanks in advance for your time.
guard status == PGConnection.StatusType.ok else { //guards from failed connections
print("Connection to database was unsuccessful")
print("Error: \(status)")
return
}
let res = p.exec(statement: sqlDropdown)
print("select statement result status: \(res.status())")
var dropdownItemsDictionary: [String: Int] = [:]
let num = res.numTuples()
let ComboBox = NSComboBox()
for x in 0.. let org_id: Int = Int(res.getFieldString(tupleIndex: x, fieldIndex: 0)!)!
let org_name: String = res.getFieldString(tupleIndex: x, fieldIndex: 1)!
let org_type: String = res.getFieldString(tupleIndex: x, fieldIndex: 2)!
let curr: String = res.getFieldString(tupleIndex: x, fieldIndex: 3)!
let mining_addr: String = res.getFieldString(tupleIndex: x, fieldIndex: 4)!
print("Entity Index = \(org_id) org_name = \(org_name) org_type = \(org_type) currency = \(String(describing: curr)) mining_addr = \(mining_addr)")
dropdownItemsDictionary[org_name] = org_id
//ComboBox.addItem(withObjectValue: org_name)
}
ComboBox.dataSource = dropdownItemsDictionary
I suppose that's an OSX App ?
Where is the code you show ? In viewDidload ? elsewhere ?
Where do you define the
NSComboBoxDataSource functions ?
Typically you should:
declare the comboBox (probably as an IBOutlet).
@IBOutlet var comboBox : NSComboBox! // name should start with lower case)
Declare its datasource, either:
- in IB, by control-drag from comboBox to its viewController and select datasource
or
- in viewDidload of the ViewController where the comboBox is declared
comboBox.datasource = self // NOT A Dictionary ; I would be surprised your code compiled with ComboBox.dataSource = dropdownItemsDictionary
make the viewController conform to protocol
NSComboBoxDataSource
Implement the needed delegate func (see doc)
To populate the comboxBox, use
func addItems(withObjectValues: [Any])
or
func addItem(withObjectValue: Any)