NSComboBox getGet更改值

Dav*_*ony 2 nscombobox swift

我是OS X应用开发的新手。我设法建立了NSComboBox(可选择的,不可编辑的),单击动作按钮后就可以得到indexOfSelectedItem,工作正常。

如何检测变化的价值?当用户更改选择时,应使用哪种功能来检测新选择的索引?

我尝试使用NSNotification,但未传递新的更改值,始终是加载时的默认值。这是因为我将postNotificationName放在错误的位置,还是应该使用其他方法来获取更改的值?

我尝试搜索网络,视频和教程,但主要是为Objective-C编写的。我在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])
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Mic*_*ael 7

您需要为实现NSComboBoxDelegate协议的组合框定义一个委托,然后使用该comboBoxSelectionDidChange(_:)方法。

最简单的方法是让您的NewProjectSetup类实现委托,如下所示:

class NewProjectSetup: NSViewController, NSComboBoxDelegate { ... etc
Run Code Online (Sandbox Code Playgroud)

然后在viewDidLoad中,还包括:

self.projNewRouter.delegate = self
// self (ie. NewProjectSetup) implements NSComboBoxDelegate 
Run Code Online (Sandbox Code Playgroud)

然后,您可以在以下位置进行更改:

func comboBoxSelectionDidChange(notification: NSNotification) {
    print("Woohoo, it changed")
}
Run Code Online (Sandbox Code Playgroud)