Create a Segmented Control in iOS7

A segmented control displays a list of options that a user can choose from. Each segment sort of looks like a radio button, the segments remains “pressed” even after the user selects the control. In this tutorial we create 2 segments inside a UISegmentedController. Each segment will display a different text value on a label.

Update: Aug 15, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use iOS7SegmentedControlTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

Go the Storyboard and drag a Segmented Control to the main view. Also drag a Label to the view. Select the label and in the Attributes Inspector set text Text Alignment to center, The Storyboard should look like this. 

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the Segmented Control to the @interface section and create the following outlet.

Ctrl and drag from the Label to the @interface section and create the following outlet.

Ctrl and drag from the Segmented Control to the @interface section and create the following action.

In ViewController.m add the following line to the end of viewDidLoad

self.textLabel.text = @"First segment selected.";

When the application starts, the first segment is selected by default, so we initially adjust our label text. Next implement the indexChanged method. This method is called when the segment index is changed by the user.

-(IBAction)indexChanged:(UISegmentedControl *)sender
{
switch (self.segmentedControl.selectedSegmentIndex)
{
case 0:
self.textLabel.text = @"First selected";
break;
case 1:
self.textLabel.text = @"Second Segment selected";
break;
default:
break;
}
}

When the selectedSegmentIndex is changed, the text of the label will be updated. The first segment has an index of 0 and the second segment has an index of 1. Build and Run the project and the text will be updated 

You can download the source code of the iOS7SegmentControlTutorial at the ioscreator repository on github.