Search code examples
swiftmacosinterface-builderxcode7nsbutton

Xcode v7.2 - New Radio Buttons: How to find selected


I am attempting to detect which Radio Button is currently selected using Xcode 7's new Radio Button template (NSButton).

I have created a simple action that will print to log the title of the sender when a radio button is selected. This does work:

@IBAction func radioButtonClicked(sender: AnyObject)
    {
    print(sender.selectedCell()!.title);
    }

But what I am really looking for is the ability to know which radio button is selected elsewhere in my codes (specifically on an IBAction for a button click). I have tried:

@IBAction func uploadButtonPressed(sender: AnyObject)
    {
    print (radioButton.selectedCell()!.title);
    }

This does compile and execute, the problem is it always gives me the title of the first radio button not the one that is actually selected.

Any ideas?


The "closest" I can get (which is not very clean, but works "kinda") is to see if radioButton.cell?state = 1. This tells me that the first radio button is selected. But this is a very poor way to code this and only allows for 2 radio button options.

if (radioButton.cell?.state == 1)
    {
    print ("Radio 1 Selected");
    }
else
    {
    print ("Radio 2 Selected");
    }

Solution

  • I ended up finding a method for this.

    First I setup a variable to store which item was checked (and pre-set the value to the value I want for the first radio button)

    var databaseUploadMethod = "trickle-add";
    

    Then I compare to see the title value of the selected item:

    @IBAction func radioButtonClicked(sender: AnyObject)
        {
        if ((sender.selectedCell()!.title) == "Trickle Add")
            {
            databaseUploadMethod = "trickle-add";
            }
        else if ((sender.selectedCell()!.title) == "Bulk Add All Now")
            {
            databaseUploadMethod = "bulk-add";
            }
        }
    

    For reference: I have two radio buttons, the first has a title of "Trickle Add" and the second is "Bulk Add All Now". Those are the values I am comparing in my if statement.