O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

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

Start Free Trial

No credit card required

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.

UISwitch used in the Settings app on an iPhone

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"

@interface ViewController ()
@property (nonatomic, strong) UISwitch *mainSwitch;
@end

@implementation ViewController

...

We can go ahead now and create our switch. Find the viewDidLoad method in your view controller’s implementation file:

- (void)viewDidLoad{
  [super viewDidLoad];
}

Let’s create our switch and place it on our view controller’s view:

- (void)viewDidLoad{
  [super viewDidLoad];

  /* Create the switch */
  self.mainSwitch = [[UISwitch alloc] initWithFrame:
                   CGRectMake(100, 100, 0, 0)];

  [self.view addSubview:self.mainSwitch];

}

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. A CGRect 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.

A switch placed on a view

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.mainSwitch setOn: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 ([self.mainSwitch isOn]){
  NSLog(@"The switch is on.");
} else {
  NSLog(@"The switch is off.");
}

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:

  [self.mainSwitch addTarget:self
                    action:@selector(switchIsChanged:)
          forControlEvents:UIControlEventValueChanged];

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:

- (void) switchIsChanged:(UISwitch *)paramSender{

  NSLog(@"Sender is = %@", paramSender);

  if ([paramSender isOn]){
    NSLog(@"The switch is turned on.");
  } else {
    NSLog(@"The switch is turned off.");
  }

}

Now go ahead and run the app on iOS Simulator. You will see messages similar to this in the console window:

Sender is = <UISwitch: 0x6e13500;
            frame = (100 100; 79 27);
            layer = <CALayer: 0x6e13700>>
The switch is turned off.
Sender is = <UISwitch: 0x6e13500;
            frame = (100 100; 79 27);
            layer = <CALayer: 0x6e13700>>
The switch is turned on.

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

Start Free Trial

No credit card required