4

我是 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])
    }
}

}

4

1 回答 1

9

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

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

class NewProjectSetup: NSViewController, NSComboBoxDelegate { ... etc

然后在viewDidLoad中,还包括:

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

然后您可以在以下位置获取更改:

func comboBoxSelectionDidChange(notification: NSNotification) {
    print("Woohoo, it changed")
}
于 2016-01-22T02:10:51.180 回答