2.2. Creating and Using Switches with UISwitch

Problem

You would like to give your users the ability to turn an option on or off.

Solution

Use the UISwitch class.

Discussion

The UISwitch class provides an On/Off control like the one shown in Figure 2-7 for Auto-Capitalization, Auto-Correction, and so on.

UISwitch used in the Settings app on an iPhone

Figure 2-7. UISwitch used in the Settings app on an iPhone

In order to create a switch, you can either use Interface Builder or simply create your instance in code. Let’s do it through code. So next the challenge is to determine which class to place your code in. It needs to be in a View Controller class, which we haven’t discussed yet, but for the a Single View Application type of app we’re creating in this chapter, you can find the view controller’s .h (header) file through a name that is based on the name of your project and ends with ViewController.h. For instance, I have named my project Creating and Using Switches with UISwitch, so the .h file of my view controller is called Creating_and_Using_Switches_with_UISwitchViewController.h. Open that file now.

Note

In the latest version of Xcode, creating a Single View Application project will create the header and implementation files of a view controller simply named ViewController. Therefore the header file of your view controller will be in the file named ViewController.h and the implementation in a file named ViewController.m.

Let’s create ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.