0

I'm using Xcode 6 and Swift to develop an OS X app, not iOS. Let's say we have two toggle buttons and each one controls a combobox. Everytime press the button, it will enable or disable the combobox it controls. I can definately set up separate actions for each button. Since I have ten buttons, this approach seems to contain a lot of redundant code.

@IBAction func clickBtn1 (sender: NSButton){
    if combobox1.enabled == true
    {
        combobox1.enabled = faulse;
    }
    else
    {
        combobox1.enabled = true;
    }
}
@IBAction func clickBtn2 (sender: NSButton){
    //same codes for combobox 2
}

Is there any way to make this simpler, such as share the action code by identify different sender, Similar to VB.NET?

UPDATE: I found a imcomplete solution for it from https://stackoverflow.com/a/24842728/2784097

now I control+drag the two buttons to the same action in ViewController.swift and also give those two buttons different tag. button1.tag=1, button2.tag = 2. The code now looks like,

//button1.tag=1, button2.tag = 2.
@IBAction func clickButton(sender:NSButton) {
    switch(sender.tag){
        case 0:
            combobox1.enabled = !combobox1.enabled;
        break;
        case 1:
            combobox2.enabled = !combobox2.enabled;
        break;
        default:
        break;
        }
 }

This solves a part of my problem. Next, I wonder is there any way to access/find the controls/components by reference, for example a string or tag or name anything. Pseudo code would like following,

//button1.tag=1, button2.tag = 2.
@IBAction func clickButton(sender:NSButton) {
    //pseudo code
    combobox[button.tag].enabled = !combobox[button.tag].enabled;
 }
Community
  • 1
  • 1
apolloneo
  • 169
  • 1
  • 2
  • 18

2 Answers2

0

You should be able to bind all of the NSButton (and NSComboBox) control events to the same buttonClicked: method. You can achieve this through Interface Builder or programmatically via the setAction: method.

Selectors in Swift are just strings, like "buttonClicked:", but I prefer to wrap them in Selector initializers for clarity (e.g. Selector("buttonClicked:")).

Erik
  • 12,730
  • 5
  • 36
  • 42
0

There are many ways to do this, here's one:

Extend the NSButton class to include a property for the combo box that it controls. That way, when in the action method, you can get a reference to the correct combo box from the instance of the button that is passed in.

  1. Create a new class MyButton that extends NSButton
  2. Add a public property to that class to hold an reference to a combo box.
  3. Replace your NSButtons with MyButtons.
  4. After the view loads, set the combo box property on each of your buttons to the correct combo box.
  5. Write a new action method that accepts a MyButton object as the sender. Get the combo box property from the sender and call combobox.enabled = !combobox.enabled.
picciano
  • 22,341
  • 9
  • 69
  • 82