Segmented Control Tutorial

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. This tutorial is made with Xcode 8 and built for iOS 10.

Open Xcode and create a new Single View Application

Choose Next. For product name, use IOS10SegmentedControlTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and drag a Segmented Control to the top of the main view. Also drag a Label to the view and place it below the Segmented Control. Select the label and give it a text of First Segment selected. The Storyboard should look like this.

Select the Label, Ctrl and drag to the Segmented Control. Select the Vertical Spacing option. 

Select the Segmented Control and select the Pin button from the Auto Layout button on the bottom-right of the Storyboard and fill in the following values. Select Add 1 Constraint.

Select both the Label and the Segmented Control by holding the Shift button. select the Align button from the Auto Layout button on the bottom-right of the Storyboard and fill in the following values. Select Add 2 Constraints.

Select the Assistant Editor and make sure ViewController.swift is visible. Ctrl and drag from the Segmented Control to the ViewController.swift and create the following Outlet.

Ctrl and drag from the Label to the ViewController.swift class and create the following Outlet.

Again, Ctrl and drag from the Segmented Control to the ViewController.swift class and create the following Action.

The indexChanged method is called when the segment index is changed by the user. Implement this method.

@IBAction func indexChanged(_ sender: AnyObject) {
    switch segmentedControl.selectedSegmentIndex
    {
    case 0:
        textLabel.text = "First Segment Selected";
    case 1:
        textLabel.text = "Second Segment Selected";
    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 IOS10SegmentedControlTutorial at the ioscreator repository on github.