In this guide, you’ll learn the steps for crafting a segmented control element with two sections, each showcasing different text values on a label. By following these steps, you’ll be proficient in constructing such components in your iOS applications.
Setting Up Your Project
Here’s what you’ll do:
- Launch Xcode and start a new Single View App application;
- Name the project “IOSSegmentedControlTutorial”, and provide the appropriate name and identifier;
- Choose Swift as your programming language and dive right in.
Designing the User Interface
You’ll then need to:
- Access the Storyboard panel and add a segmented control component to the upper section of the primary view;
- Drag and drop a label beneath the segmented control;
- Set the label text to “First Segment Chosen”;
- Once the labels are set, proceed to the subsequent step.
Layout and Auto Constraints
To ensure the correct layout:
- Opt for “Resolve Auto Layout issues”;
- Then choose “Reset to Suggested Constraints”;
- Now, let’s transition to creating outlets.
Creating Outlets
Here’s the procedure:
- Launch the Assistant Editor and make sure ViewController.swift is visible;
- Using the Ctrl key, drag the Segmented Control component into ViewController.swift to establish an outlet;
- Repeat this process for the label.
Implementing the Segment Change Action
<alt=""/>
Perform the following actions:
Drag from the segmented control to the ViewController.swift class to generate an Action.
Implement the indexChanged method to respond to segment alterations.
@IBAction func indexChanged(_ sender: Any) {
switch segmentedControl.selectedSegmentIndex {
case 0:
textLabel.text = "First Segment Chosen"
case 1:
textLabel.text = "Second Segment Chosen"
default:
break
}
}
Access the Source Code
You can download the IOSSegmentedControlTutorial source code from the ioscreator repository on GitHub.
Conclusion
From this lesson, you’ve gained insight into creating and executing a segmented control component in an iOS app. This tool is invaluable for enhancing user interaction and offering clear choices within your app’s interface.