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

Figure 2-26. A segmented control displaying four options
Discussion
A segmented control is a UI component that allows you to display,
in a compact UI, 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 .h file:
#import <UIKit/UIKit.h>@interfaceGrouping_Compact_Options_with_UISegmentedControlViewController:UIViewController@property(nonatomic,strong)UISegmentedControl*mySegmentedControl;@end
And create the segmented control in the viewDidLoad method of your view
controller:
-(void)viewDidLoad{[superviewDidLoad];self.view.backgroundColor=[UIColorwhiteColor];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 ...
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