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

How to know which NSCombobox selector calling the Delegate

我在 SWIFT 中为 OS X App 编写了以下代码,代码运行良好(NSComboBox 仅 select 可用,不可编辑)

我有这两个 IBOutlet projNewProjTypeprojNewRouter,当我更改任一 NSComboBox 的 selection 时,我可以看到正确的 selected索引值和字符串值,但如何检查返回的索引值是否来自 projNewProjType NOT projNewRouter in the comboBoxSelectionDidChange()

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

您已经知道您的两个 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")
    }

您可以在 IB 中为您的 NSComboBoxes 设置标识符。 Select 您的组合框并选择身份检查器和名称标识符。那么你可以这样做:

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