O'Reilly logo

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

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