1.8. Grouping Compact Options with UISegmentedControl
Problem
You would like to present a few options to your users from which they can pick an option, through a UI that is compact, simple, and easy to understand.
Solution
Use the UISegmentedControl
class, an example of which is shown in Figure 1-22.

Figure 1-22. A segmented control displaying four options
Discussion
A segmented control is a UI component that allows you to display,
in a compact UI, a series of options for the user to choose from.
To show a segmented control, create an instance of UISegmentedControl. Let’s start with our view
controller’s .m file:
#import "ViewController.h"@interfaceViewController()@property(nonatomic,strong)UISegmentedControl*mySegmentedControl;@end@implementationViewController...
And create the segmented control in the viewDidLoad method of your view
controller:
-(void)viewDidLoad{[superviewDidLoad];NSArray*segments=[[NSArrayalloc]initWithObjects:@"iPhone",@"iPad",@"iPod",@"iMac",nil];self.mySegmentedControl=[[UISegmentedControlalloc]initWithItems:segments];self.mySegmentedControl.center=self.view.center;[self.viewaddSubview:self.mySegmentedControl];}
We are simply using an array of strings to provide the different
options that our segmented control has to display. We initialize our
segmented control using the init initializer and pass the array of strings and ...WithObjects:
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access