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.

A segmented control displaying four options

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>

@interface Grouping_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{
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];
  NSArray *segments = [[NSArray alloc] initWithObjects:
                       @"iPhone",
                       @"iPad",
                       @"iPod",
                       @"iMac", nil];

  self.mySegmentedControl = [[UISegmentedControl alloc]
                             initWithItems:segments];
  self.mySegmentedControl.center = self.view.center;
  [self.view addSubview: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 ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.