Search code examples
macosswift2nscombobox

Populate NSComboBox from Data Source


This code compiles OK, but the ComboBox (cbxColors) is empty - not populated from the Data Source (array: COLORS_OF). Uses Data Source is checked in IB.

func numberOfItemsInComboBox() returns the correct result: 5.

func comboBox() is not doing its job.

What am I missing?

EDITED: Now working.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSComboBoxDelegate, NSComboBoxDataSource {

@IBOutlet weak var window: NSWindow!


func applicationDidFinishLaunching(aNotification: NSNotification) {

    cbxColors.dataSource = self

    numberOfItemsInComboBoxCell(cbxColors)
    comboBoxCell(cbxColors, objectValueForItemAtIndex: 0)
}

func applicationWillTerminate(aNotification: NSNotification) {

}

@IBOutlet weak var cbxColors: NSComboBox!
@IBOutlet weak var txtResult: NSTextField!


@IBAction func actColors(sender: NSComboBox) {
    // display User selected item in 'txtResult'
}

func numberOfItemsInComboBoxCell(aComboBox: NSComboBox) -> Int {
    return(COLORS_OF.count)
}

func comboBoxCell(aComboBox: NSComboBox, objectValueForItemAtIndex index: Int) -> AnyObject {
    return(COLORS_OF[index])
}

let COLORS_OF = [ "Blue", "Green", "Purple", "Red", "Yellow" ]
} 

Solution

  • You probably forgot to check Uses Data Source or you have to delete datasource connection and reconnect it again (weird bug of Xcode).

    enter image description here

    Other then that if your outlets are correctly hooked your code works.

    enter image description here