C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: An outlet is a reference in our Swift file we can use to manipulate the Switch with code.
Names: Please select useful names for the UISwitch and UILabel. I used simpleSwitch and simpleLabel.
Example ViewController: Swift
//
// ViewController.swift
// ExampleTimeA
//
// ...
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var simpleSwitch: UISwitch!
@IBOutlet weak var simpleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
So: Click and drag from the circle near "Primary Action Triggered" to the ViewController.swift file.
And: If the Switch is on, we set the text of our UILabel to a certain string. If it is off, we use another string.
Example UISwitch code: Swift
//
// ViewController.swift
// ExampleTimeA
//
// ...
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var simpleSwitch: UISwitch!
@IBOutlet weak var simpleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func actionTriggered(sender: AnyObject) {
// Get value of "on" to determine current state of UISwitch.
let onState = simpleSwitch.on
// Write label text depending on UISwitch.
if onState {
simpleLabel.text = "Switch is on"
}
else {
simpleLabel.text = "Off"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Label: The UILabel's text is changed by the Swift code. So we succeed in detecting when the Switch is changed by the iPhone user.