Search code examples
cocoaswiftnscombobox

How can I get a populated combobox to display its options in Swift?


With this code I'm able to populate the items in an NSComboBox, but the combobox itself is always empty when you expand it in the app.

The number of items being logged is accurate. I know this is rather basic, but I've read and re-read the docs at developer.apple.com and have looked for examples of comboboxes in Swift to no avail, which is quite surprising to me.

@IBOutlet var someComboBox: NSComboBox!

override func viewDidLoad() {
    super.viewDidLoad()

    someComboBox = NSComboBox()
    someComboBox.addItemWithObjectValue("Foo")
    someComboBox.addItemWithObjectValue("Bar")
    someComboBox.addItemWithObjectValue("Baz")
    println(someComboBox.numberOfItems)
}

and the result: enter image description here


Solution

  • Your comboBox is an IBOutlet, so the object is created for you already by the Storyboard; you just need to initialize it. So remove:

    someComboBox = NSComboBox()
    

    because that is allocating a new combo box and overwriting the reference to the one created in the Storyboard. Your new comboBox is not the one that is on screen.