How to Switch View Controllers Using iOS UISegmentedControl

One of the typical usages of iOS UISegmentedControl is for switching between different switch view controllers. UISegnmentedControl is a horizontal bar that comes with multiple segments. Each of these segments work as a discrete button to display an image or text.

In simple words, UISegmentedControl is used to show or hide data based on selected category in the view controller.

UISegmentedControl Example

In our today’s iOS app tutorial, we’ll demonstrate the implementation process of UISegmentedControl for you to implement in your iPhone app development project.

Let’s Get Started

Open XCode and create a new project under the file menu.

samplesegment1

In the next tab, select Single View Application as a project type.

samplesegment2

Write project name and other details.

samplesegment3

Once you create a new project, go to Main.storyboard and select ViewController.

samplesegment4

Now drag and drop UISegmentedControl from “Show the object library” section.

samplesegment5

samplesegment6

Now select SegmentedControl and see the attribute inspector which has properties of SegmentedControl. We can manage the segment count, segment titles, image, selection, etc.

samplesegment7

samplesegment8

Now we set outlet UISlider in ViewController as well as add a view for see the segment change event.

@IBOutlet weak var segControl: UISegmentedControl!
@IBOutlet weak var vwColorChange: UIView!

samplesegment9

samplesegment10

Set IBAction for UISegmentedControl.

@IBAction func actionSegmentAction(sender:UISegmentedControl) {
switch segControl.selectedSegmentIndex {
case 0:
vwColorChange.backgroundColor = UIColor.greenColor()
case 1:
vwColorChange.backgroundColor = UIColor.blueColor()
case 2:
vwColorChange.backgroundColor = UIColor.magentaColor()
default:
vwColorChange.backgroundColor = UIColor.greenColor()
}
}

samplesegment11

And done!

Now that you know the implementation process of iOS UISegmentedControl for iPhone app development, you can implement it in an iPhone app to create switch views for different purposes.

However, if you’ve doubts, then you can contact our development team for help.

Grab a free copy of Custom Segmented Control Example demo from Github.

Author Bio
Hitesh Trivedi
Hitesh Trivedi
Designation: iOS Team Lead

Hitesh Trivedi is an iOS Team Lead at Space-O Technologies. He has over 10 years of experience in iOS app development. He has guided to develop over 100 iPhone apps with unique features and functionalities. He has special expertise in Swift and Objective-C.