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.
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.
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
self.textLabel.text = @"Segment 1 selected.";
Create the segmentedControllerIndexChanged method, when the selectedSegmentIndex is selected, the text of the label will be updated.
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.