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 9 and built for iOS 11.

Open Xcode and create a new Single View App.

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

Go to the Storyboard and drag a Button, a Text Field 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 all three objects and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 3 Constraints".

Select the Button and select the Auto Layout "Add New Constraints" button. Pin the Button to the top and and click "Add 1 Constraint".

Select the Text Field and Ctrl and Drag to the Button. Select Vertical Spacing. Select Trh Switch and Ctrl And Drag to the Text Field. Select Vertical Spacing.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Text Field 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.

Next, implement the buttonClicked method.

 @IBAction func buttonClicked(_ sender: Any) {
    if stateSwitch.isOn {
        textField.text = "The Switch is Off"
        stateSwitch.setOn(false, animated:true)
    } else {
        textField.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: UIControlEvents.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 {
        textField.text = "The Switch is On"
    } else {
        textField.text = "The Switch is Off"
    }
}

The text of the Text Field will be updated according to the state of the switch. Build and Run the project and flip the switch or press the button and the text of the Text Field will be updated.

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