iOS: Segment Control
Segment control is characterized as a horizontal control that manages several segments, each of which is controlled by a different button. Multiple views can be presented within a single view controller by utilizing a segment control, where each view is displayed using a separate button.
The declaration of the segment control is as follows.
class UISegmentControl : UIControl
Example
To demonstrate this, we will incorporate the segment control into our interface builder and utilize it to show the different XIB files that we have generated.
Interface Builder
In this example, the individual views on the occurrence of horizontal segment control are displayed using two XIBs. Segment control, which regulates how the views are displayed appropriately, is a feature of the main storyboard.
What is a XIB file?
What is called an XML interface builder is XIB. With the aid of cocoa and carbon, we can create graphical user interfaces thanks to the interface builder. In order to offer the application’s user interface, XIB files are loaded during runtime. The XIB files, which are representations of UIView, are saved as NIB or XIB files.
VC1.xib
The VC.xib file can be seen in the picture below.
VC2.xib
The VC2.xib file can be seen in the image below.
ViewController.swift
We will establish the action connection for the segment control in the ViewController.swift file. This connection will be alerted each time the valueChanged event for the segment control is triggered.
It switches between the Segment Control valueChanged event and the VC1.xib and VC2.xib.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var viewContainer: UIView!
var views = Array()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
views.append(VC1().view!)
views.append(VC2().view!)
for v in views{
viewContainer.addSubview(v)
}
viewContainer.bringSubviewToFront(views[0])
}
@IBAction func switchViewAction(_ sender: UISegmentedControl) {
viewContainer.bringSubviewToFront(views[sender.selectedSegmentIndex])
}
}