0

I have 2 radio buttons and a button to calculate some code. The point is to only allow for 1 of the radio buttons to be selected in order for the calculate button to do its job, but for some reason when I build my project and select one of the radio buttons, I can no longer unclick it. Does anyone know why this is the case?

loltospoon
  • 239
  • 1
  • 9
  • Provide a snippet of your code so that we can figure out your problem. For now, it looks as if you are not keeping track of each button's current state whenever it is pressed and due to which when u repress an already selected radio button, it gets selected again rather than getting deselected. If you provide some code, we ll be able to help u in a better way. – Rahul Mar 29 '17 at 09:37
  • Have you read http://stackoverflow.com/questions/31104025/how-to-create-nsradiobutton-group-in-xcode-7-osx? – thm Mar 29 '17 at 13:43
  • @Rahul I think that's my problem....I only dragged the radio buttons in from the object library, I never really wrote any code for them...I only read if they were selected or not. – loltospoon Mar 31 '17 at 00:06
  • @thm what does it mean when they say "when they have the same superview and -action method" – loltospoon Mar 31 '17 at 00:48
  • I didn't connect them as an action I only did it like an outlet and am reading their individual states. – loltospoon Mar 31 '17 at 00:51
  • @loltospoon Not connecting them to an action is exactly what's missing, see my answer. – thm Apr 05 '17 at 08:30

1 Answers1

0

If you follow this hint that Interface Builder shows for radio buttons, it works:

For a single choice among mutually-exclusive options.

For apps running on 10.8 and later, creating radio groups with individual NSButton objects (rather than an NSMatrix) is preferred.

Radio buttons automatically act as a group (selecting one button will unselect all other related buttons) when they have the same superview and -action method.

Just putting them all in the same superview is not enough (just tested and confirmed this), you also need to wire them up to the same action.

Put them all in the same superview:

Radio Buttons in Stack View

Wire each of them up to the same action:

Radio Button Action

@IBAction func clickedRadioButton(_ sender: NSButton)
{
    print("Clicked \(sender.title)")
}

Then, every time you select one of the radio buttons, the other ones will automatically be deselected and your action method will be invoked with the button that you selected.

thm
  • 1,217
  • 10
  • 12