Radio Button In macOS Xcode
To add a RadioButton to a NSView, there are two ways to achieve, the first one is by adding it programmatically and the second one is with Interface Builder (Xcode 7 onwards)
Here first we create a
1) NSButtonCell object and assign a title to it.
2) Then create NSMatrix object of model , NSRadioModeMatrix and number of Rows = 3 and number of columns as 1.
3) After creating the matrix, you can simple assign the title to each elements
But, here will have to worry about autolayout and other stuff while adding programmatically.
Apart from this approach of NSMatrix is discouraged, from OS X v10.8.
I usually add them a NSStackView and link all actions to a COMMON action handler.
Please read Xcode7 release notes for below statement
Rules to achieve this are listed below.
Rule Number 1: => All Radio buttons should belong to the same superview.
ex: In my case Male, Female and Unknown refer to the same superview.
Rule Number 2: => All Radio buttons should have same action method.
The Console prints the below output, when I tap on each radio button.
@IBAction Connection for one of the button is shown below.
First Way
Adding the options programmatically. Please refer to Button Programming tips.Here first we create a
1) NSButtonCell object and assign a title to it.
2) Then create NSMatrix object of model , NSRadioModeMatrix and number of Rows = 3 and number of columns as 1.
3) After creating the matrix, you can simple assign the title to each elements
But, here will have to worry about autolayout and other stuff while adding programmatically.
Apart from this approach of NSMatrix is discouraged, from OS X v10.8.
Second Way(Easiest Way , less code)
This one is much simpler and takes advantage of Xcode Interface builder and can be achieved from Xcode 7 onwards only.I usually add them a NSStackView and link all actions to a COMMON action handler.
Please read Xcode7 release notes for below statement
- The template for Radio buttons in the Interface Builder object library is now implemented as individual
NSButton
objects, rather than the olderNSMatrix
, which is discouraged on OS X v10.8 and later. 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. (16965941)
Rules to achieve this are listed below.
Rule Number 1: => All Radio buttons should belong to the same superview.
ex: In my case Male, Female and Unknown refer to the same superview.
Rule Number 2: => All Radio buttons should have same action method.
- @IBAction func radioButtonEvents(_ sender: AnyObject) {
- if let buttonObject = sender as? NSButton {
- print("Button Title => \(buttonObject.title)")
- }
- }
ButtonObject Male
ButtonObject Female
ButtonObject Unknown
Comments
Post a Comment