Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSComboBox getGet value on change

I am new to OS X app development. I manage to built the NSComboBox (Selectable, not editable), I can get it indexOfSelectedItem on action button click, working fine.

How to detect the the value on change? When user change their selection, what kind of function I shall use to detect the new selected index?

I tried to use the NSNotification but it didn't pass the new change value, always is the default value when load. It is because I place the postNotificationName in wrong place or there are other method should use to get the value on change?

I tried searching the net, video, tutorial but mostly written for Objective-C. I can't find any answer for this in SWIFT.

import Cocoa

class NewProjectSetup: NSViewController {

    let comboxRouterValue: [String] = ["No","Yes"]

    @IBOutlet weak var projNewRouter: NSComboBox!

    @IBAction func btnAddNewProject(sender: AnyObject) {
        let comBoxID = projNewRouter.indexOfSelectedItem
        print(“Combo Box ID is: \(comBoxID)”)
    }

    @IBAction func btnCancel(sender: AnyObject) {
        self.dismissViewController(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        addComboxValue(comboxRouterValue,myObj:projNewRouter)
        self.projNewRouter.selectItemAtIndex(0)

        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
        self,
        selector: “testNotication:”,
        name:"NotificationIdentifier",
        object: nil) 

        NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: projNewRouter.indexOfSelectedItem)
}

func testNotication(notification: NSNotification){
    print("Found Combo ID  \(notification.object)")
}

func addComboxValue(myVal:[String],myObj:AnyObject){
    let myValno: Int = myVal.count
    for var i = 0; i < myValno; ++i{
        myObj.addItemWithObjectValue(myVal[i])
    }
}

}

like image 943
David Evony Avatar asked Jan 07 '23 18:01

David Evony


1 Answers

You need to define a delegate for the combobox that implements the NSComboBoxDelegate protocol, and then use the comboBoxSelectionDidChange(_:) method.

The easiest method is for your NewProjectSetup class to implement the delegate, as in:

class NewProjectSetup: NSViewController, NSComboBoxDelegate { ... etc

Then in viewDidLoad, also include:

self.projNewRouter.delegate = self
// self (ie. NewProjectSetup) implements NSComboBoxDelegate 

And then you can pick up the change in:

func comboBoxSelectionDidChange(notification: NSNotification) {
    print("Woohoo, it changed")
}
like image 190
Michael Avatar answered Jan 18 '23 23:01

Michael