Create a UISegmentedControl

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 textvalue on a label.

Update: Feb 28, 2014. This tutorial is made with Xcode 4 and targeted for iOS 6. The fully updated version for iOS7 and Xcode 5 is available here.
Update: Aug 15, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

This tutorial is made with Xcode 4 and targeted for iOS6. For an updated tutorial made with Xcode 5 and targeted for iOS7 click here.

Open Xcode and create a new Single View Application. For product name, use SegmentedControllerDemo 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, and that the Use Storyboards is deselected and Use Automatic Reference Counting checkboxes is selected.

First, we build The User Interface. Open ViewController.xib. Drag a segmentedController to the view. Drag a UILabel to the view.

Go to ViewController.m. Create the following properties in the @interface section

@property (nonatomic,weak) IBOutlet UILabel *textLabel;
@property (nonatomic,weak) IBOutlet UISegmentedControl *segmentedControl;

When a segment is selected the following method is triggered. Declare the following IBAction method.

- (IBAction)segmentedControlIndexChanged;

Go back to ViewController.xib. Make the follwoing connections.

  • UILabel -> textLabel
  • Segmented Control -> segmentedControl
  • Segmneted Control -> segmentedControlIndexChanged

In ViewController.m in ViewDidLoad set the text of our label. Change viewDidLoad in

- (void)viewDidLoad 
[super viewDidLoad];

self.textLabel.text = @"Segment 1 selected.";

Create the segmentedControllerIndexChanged method, when the selectedSegmentIndex is selected, the text of the label will be updated.

-(IBAction) segmentedControlIndexChanged
switch (self.segmentedControl.selectedSegmentIndex)
case 0:
self.textLabel.text =@"Segment 1 selected.";
case 1: self.textLabel.text =@"Segment 2 selected.";

Build and Run, When you select the first segment button the view look like this.

and when you select the second button the view look like this


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