Switch iOS Tutorial

The switch control is used to control the state of a Boolean object. In this tutorial the state will be changed and this state will also be displayed inside a Label.This tutorial is made with Xcode 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use IOSSwitchTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Storyboard

Go to the Storyboard and drag a Button, a Label and a Switch to the main view. Give the button a title of "Change State" and the Text Field a text of "The Switch is On". The Storyboard will look like this.

Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

Outlet and Action Connections

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Text Label to the ViewController class and create the following Outlet

Next, Ctrl and drag from the Switch and create another outlet

Ctrl and drag from the Button and create the following action.

Code Implementation

Implement the buttonClicked method.

 @IBAction func buttonClicked(_ sender: Any) {
    if stateSwitch.isOn {
        textLabel.text = "The Switch is Off"
        stateSwitch.setOn(false, animated:true)
    } else {
        textLabel.text = "The Switch is On"
        stateSwitch.setOn(true, animated:true)
    }
}

If the switch is on, the Text Field text is updated and the switch state is changed using the setOn:animated method of the UISwitch class. Otherwise, when the switch is off, the state is changed to on. Of course, we also want to update the Text Field text when we flip our switch. manually by clicking the switch. Change the viewDidLoad method in

override func viewDidLoad() {
    super.viewDidLoad()
        
    stateSwitch.addTarget(self, action: #selector(stateChanged), for: .valueChanged)
}

When the switch is flipped the UIControlEventValueChanged event is triggered and the stateChanged method will be called.

 @objc func stateChanged(switchState: UISwitch) {
    if switchState.isOn {
        textLabel.text = "The Switch is On"
    } else {
        textLabel.text = "The Switch is Off"
    }
}

The text of the Label will be updated according to the state of the switch.

Run Project

Build and Run the project and flip the switch or press the button and the text of the Text Label will be updated.

You can download the source code of the IOS11SwitchTutorial at the ioscreator repository on Github.