如何知道调用Delegate的NSCombobox选择器

时间:2016-01-22 12:35:04

标签: swift macos nscombobox

我在SWIFT for OS X App中编写了以下代码,代码工作正常(NSComboBox只能选择,不可编辑)

我有这两个IBOutlet projNewProjTypeprojNewRouter,当我更改任一NSComboBox的选择时,我可以看到正确选择的Index值和String值但是如何检查返回索引值来自projNewProjType

中的projNewRoutercomboBoxSelectionDidChange()
import Cocoa
class NewProjectSetup: NSViewController, NSComboBoxDelegate {
  let comboxProjValue: [String] = [“No”,”Yes”]
  let comboxRouterValue: [String] = ["No","Yes"]

  @IBOutlet weak var projNewProjType: NSComboBox!
  @IBOutlet weak var projNewRouter: NSComboBox!


  @IBAction func btnAddNewProject(sender: AnyObject) {
    print(“Add New Button Pressed!”)
  }

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

  override func viewDidLoad() {
    super.viewDidLoad()
    addComboxValue(comboxProjValue,projNewProjType)
    addComboxValue(comboxRouterValue,projNewRouter)

    self.projNewProjType.selectItemAtIndex(0)
    self.projNewRouter.selectItemAtIndex(0)

    self.projNewProjType.delegate = self
    self.projNewRouter.delegate = self
  }


  func comboBoxSelectionDidChange(notification: NSNotification) {
    let comboBox: NSComboBox = (notification.object as? NSComboBox)!

    print("comboBox comboBox: \(comboBox)")
    /* This printed “<NSComboBox: 0x6000001e1a00>”*/

    print("comboBox objectValueOfSelectedItem: \(comboBox.objectValueOfSelectedItem)")
    /* This printed the correct selected String value */

    print("comboBox indexOfSelectedItem: \(comboBox.indexOfSelectedItem)")
    /* This printed the correct selected Index value */        
  }

  /* Add value to Combo box */
  func addComboxValue(myVal:[String],myObj:AnyObject){
    let myValno: Int = myVal.count
    for i in 0..<myValno{
        myObj.addItemWithObjectValue(myVal[i])
    }
  }
}

2 个答案:

答案 0 :(得分:3)

您已经知道两个NSComboBox插座的地址,并且您知道哪个NSComboBox导致该通知触发的地址,那么为什么不执行以下操作:

func comboBoxSelectionDidChange(notification: NSNotification) {
    let comboBox: NSComboBox = (notification.object as? NSComboBox)!

    if comboBox == self.projNewProjType
    {
        print("selection changed via self.projNewProjType")
    }
    if comboBox == self.projNewRouter
    {
        print("selection changed via self.projNewRouter")
    }

答案 1 :(得分:2)

您可以在IB中为NSComboBox设置标识符。选择您的组合框,然后选择身份检查器和名称标识符。然后你可以这样做:

if comboBox.identifier == "someIdentifier" {
    // Do something
}