With Safari, you learn the way you learn best. Get unlimited access to videos, live online training,
learning paths, books, tutorials, and more.

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.

So we are allocating an object of type UISwitch and using the initWithFrame: initializer to initialize our
switch. Note that the parameter that we have to pass to this method is
of type CGRect. ACGRect denotes the
boundaries of a rectangle using the (x,y) position
of the top-left corner of the rectangle and its width and height. We can
construct a CGRect using the CGRectMake inline method, where the first two
parameters passed to this method are the (x,y)
positions and the next two are the width and height of the
rectangle.

After we’ve created the switch, we simply add it to our view
controller’s view.

Now let’s run our app on iOS Simulator. Figure 1-8 shows what happens.

Figure 1-8. A switch placed on a view

As you can see, the switch’s default state is off. We can
change this by changing the value of the on property of the instance of UISwitch. Alternatively, you can call the
setOn: method on the switch, as shown
here:

[self.mainSwitchsetOn:YES];

You can prettify the user interaction by using the setOn:animated: method of the switch. The
animated parameter accepts a Boolean
value. If this Boolean value is set to YES, the change in the switch’s state (from on
to off or off to on) will be animated, just as if the user were
interacting with it.

Obviously, you can read from the on property of the switch to find out whether
the switch is on or off at the moment. Alternatively, you can use the
isOn method of the switch, as shown
here:

If you want to get notified when the
switch gets turned on or off, you will need to add your class as the
target for the switch, using the addTarget:action:forControlEvents: method of
UISwitch, as shown here:

Then implement the switchIsChanged: method. When the runtime
calls this method for the UIControlEventValueChanged event of the
switch, it will pass the switch as the parameter to this method, so you
can find out which switch has fired this event: