O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required