How to use UISwitch control in Swift

Last Updated: October 8, 2017

This is UISwitch example when you build iOS applications

Fist I am going to create sigleview application and add UILable, UISwitch into the ViewController as shown in the following image
switch 1

Next you can connect UISwitch and UILable with ViewController.swift with IBAction and IBOutlet

 

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var labelState: UILabel!
    @IBAction func switchValueChanged(_ sender: UISwitch) {
        if(sender.isOn){
            labelState.text = "Switch is ON"
        }else{
            labelState.text = "Switch is OFF" 
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

You have the switchValueChanged() function to get the status of the UISwitch control. When the value of the switch is changed this function will be called

Test