How to group radio buttons (from storyboard) in cocoa application?
Asked Answered
J

4

5

I'm trying to group 2 radio buttons in cocoa application.

but unlike in iOS, where you can connect the buttons with control-drag (as shown in the picture)enter image description here

in cocoa application I didn't find any elegant way to do so...

any suggesting before I do something ugly?

Julianjuliana answered 16/5, 2016 at 8:48 Comment(0)
J
1

so here is my not very elegant solution -

  1. define array of buttons in the class:

NSArray* _radioButtonsArray;

  1. initialize it in viewDIdLoad:

    _radioButtonsArray = [[NSArray alloc] initWithObjects:_radioButton1,_radioButton2,_radioButton3, nil];
    
  2. define a radioButtonIsPressed method and connect it to all radio buttons as an action:

    -(IBAction)radioButtonIsPressed:(id)sender{ for (NSButton* btn in _radioButtonsArray){ if (btn != sender) [btn setState:0]; } }

Julianjuliana answered 16/5, 2016 at 9:7 Comment(0)
G
14

NSMatrix used to be the solution, but it is now discouraged:

NOTE: Use of NSMatrix is discouraged in apps that run in OS X v10.8 and later. If you need to create a radio button group in an app that runs in OS X v10.8 and later, create instances of NSButton that each specify a button type of NSRadioButton and specify the same action and the same superview for each button in the group.

If all buttons call the same action method and are in the same superview, Cocoa automatically selects the clicked button and deselects the previous button and -- no code necessary to do that.

Gunsel answered 16/5, 2016 at 16:34 Comment(2)
The last part of this answer is the only relevant part: just assign the same event handler and everything works as expected.Calci
Right you are, Ely, so I shortened the answer.Gunsel
S
4

I found this (maybe not elegant):

  1. control-drag a single radio button to a create an sent-action.
  2. control-drag the other button(s) to the same (empty) function.

You have to hover over the function to get it connected.

Now they are grouped.

Scutcheon answered 28/5, 2016 at 20:19 Comment(1)
this is amazingCathleencathlene
J
1

so here is my not very elegant solution -

  1. define array of buttons in the class:

NSArray* _radioButtonsArray;

  1. initialize it in viewDIdLoad:

    _radioButtonsArray = [[NSArray alloc] initWithObjects:_radioButton1,_radioButton2,_radioButton3, nil];
    
  2. define a radioButtonIsPressed method and connect it to all radio buttons as an action:

    -(IBAction)radioButtonIsPressed:(id)sender{ for (NSButton* btn in _radioButtonsArray){ if (btn != sender) [btn setState:0]; } }

Julianjuliana answered 16/5, 2016 at 9:7 Comment(0)
M
0

I control-drag the single radio button to create an IBAction. Then I copy/past the radio button onto the same view. Now there are two with the same IBAction. Cocoa treats them as grouped.

Memory answered 28/10, 2017 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.