UISwitch Tutorial in iOS8 with Swift

The switch control is used to display the state of a Boolean object in iOS8. You use the UISwitch class to create and manage the On/Off buttons. In this tutorial we will change the state of the switch using a button and also we will display the current state of the switch. This tutorial is written in Swift so you will need Xcode 6. It can be downloaded at Apple's developer portal.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftUISwitchTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard and change the width to compact. This will change the view to a iPhone portrait mode. 

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 should look like this.

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the Text Field to the ViewController class to 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: UIButton) {
  if mySwitch.on {
    myTextField.text = "The Switch is Off"
    println("Switch is on")
    mySwitch.setOn(false, animated:true)
  } else {
      myTextField.text = "The Switch is On"
      mySwitch.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 message in

mySwitch.addTarget(self, action: Selector("stateChanged:"), forControlEvents: UIControlEvents.ValueChanged)

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

func stateChanged(switchState: UISwitch) {
  if switchState.on {
    myTextField.text = "The Switch is On"
  } else {
      myTextField.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 iOS8SwiftUISwitchTutorial at the ioscreator repository on github.