1.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 1-7 for
Auto-Capitalization, Auto-Correction, and so on.

Figure 1-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 single-view application type of app we’re creating in this chapter, you can find the view controller’s .m (implementation) file as ViewController.m. Open that file now.
Let’s create a property of type UISwitch and call it
mainSwitch:
#import "ViewController.h"@interfaceViewController()@property(nonatomic,strong)UISwitch*mainSwitch;@end@implementationViewController...
We can go ahead now and create our switch. Find the viewDidLoad method in your view controller’s
implementation file:
-(void)viewDidLoad{[superviewDidLoad];}
Let’s create our switch and place it on our view controller’s view:
-(void)viewDidLoad{[superviewDidLoad];/* Create the switch */self.mainSwitch=[[UISwitchalloc]initWithFrame:CGRectMake(100,100,0,0)];
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access