

Segmented Control iOS Tutorial
source link: https://www.tuicool.com/articles/hit/bEZf6nn
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A segmented control is a set of two or more segments, each of which functions as a mutually exclusive button. Within the control, all segments are equal in width. 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 10 and built for iOS 12.
Open Xcode and create a new Single View App.

For product name, use IOSSegmentedControlTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

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 "Resolve Auto Layout Issues" button on the bottom-right of the Interface Builder and choose "Reset to Suggested 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: Any) { 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 IOSSegmentedControlTutorial at the ioscreator repository on github .
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK