iOS UI Controls
iOS: Switch
The switch is simply the UIControl that gives the user the option to turn anything on or off. The UISwitch class, a subclass of UIControl, defines the attributes and methods that control a switch’s state.
Here is how the UISwitch class is declared.
class UISwitch : UIControl
A switch can only be in one of two states at once: on or off. An action call is made to the action connection linked to the swift and the valueChanged event is raised when the user attempts to modify the state of the switch.
Using the properties listed in the UISwitch class, we may alter the swift’s look.
The following procedures can be used to add a switch to the interface.
1. Drag the UISwitch class object to the storyboard builder after creating it or finding it in the object library.
2. To alter the switch’s look at runtime, provide an outlet for it in the ViewController class.
3. In the ViewController class, provide an action connection method for the switch that may be called at runtime when the switch’s valueChanged event is triggered.
Example
Here, we’ll construct a very basic example in which we’ll keep the switch in its current state and write a function that receives a callback whenever the switch changes.
Interface Builder
In this instance, we’ve made a very basic storyboard using the label and the switch. Here, we’ll utilize the label to indicate whether the switch is in the on or off position. The outlets in the ViewController.swift file are linked to the label and switch.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var msgLbl: UILabel!
@IBOutlet weak var mySwitch : UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func switchValueChanged(_ sender: UISwitch) {
if(mySwitch.isOn){
msgLbl.text = "Switch is On"
}
else {
msgLbl.text = "Switch is Off"
}
}
}
Output