2.6. 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-21.

A segmented control displaying four options

Figure 2-21. 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

Now synthesize the mySegmentedControl property:

#import "Grouping_Compact_Options_with_UISegmentedControlViewController.h"

@implementation
  Grouping_Compact_Options_with_UISegmentedControlViewController

@synthesize mySegmentedControl;

...

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 ...

Get iOS 5 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.