Setup UISwitch Recipe

October 6, 2019 ยท 1 minute read

Setup a UISwitch

  1. Drag on a switch
  2. Set it’s initial “State” (on or off)
  3. Create its outlet
  4. Go to its “Connections Inspector”
  5. Locate its “Primary Action Triggered” even and drag onto file to bring it the switch’s action 6a. Have the switch do work (see the code snippet below). Also need to make a connection to the switch’s “Value Changed” in Sent Actions.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var simpleSwitch: UISwitch!
@IBOutlet weak var simpleLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
}

6b. @IBAction func actionTriggered(sender: AnyObject) {

    // 7. Get value of "on" to determine current state of UISwitch.
    let onState = simpleSwitch.on

    // 8. Write label text depending on UISwitch.
    if onState {
        simpleLabel.text = "Switch is on"
    }
    else {
        simpleLabel.text = "Off"
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

Subscribe to my email list for a monthly newsletter and special updates!