iOS 7 Controls - UISwitch Tutorial

The switch control is used to display the state of a Boolean object in iOS7. 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.

Update: July 21, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use iOS7UISwitchTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices. 

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

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the Text Field to the @interface section 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)buttonClicked:(UIButton *)sender {
if ([self.mySwitch isOn]) {
self.myTextField.text = @"The Switch is Off";
NSLog(@"Switch is on");
[self.mySwitch setOn:NO animated:YES];
} else {
self.myTextField.text = @"The Switch is On";
[self.mySwitch setOn:YES animated:YES];
}
}

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. Change the viewDidLoad message in

- (void)viewDidLoad
{
[super viewDidLoad];

[self.mySwitch addTarget:self
action:@selector(stateChanged:) forControlEvents:UIControlEventValueChanged];
}

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

- (void)stateChanged:(UISwitch *)switchState
{
if ([switchState isOn]) {
self.myTextField.text = @"The Switch is On";
} else {
self.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 iOS7UISwitchTutorial at the ioscreator repository on github.