You use the UISwitch class to create and manage the On/Off buttons used, for example, in the Settings app for options such as Airplane Mode and Bluetooth. These objects are known as switches.

The UISwitch class declares a property and a method to control its on/off state. As with UISlider, when the user manipulates the switch control (“flips” it) a UIControlEventValueChanged event is generated, which results in the control (if properly configured) sending an action message. Apple Documentation

Steps:

  1. Create a new Xcode Project for (Single View Application).
  2. Give Project a name ( Lets say CustomizeSwitch).
  3. Click next button and the Project will be created.
  4. Now go to Main StoryBoard of the Project and In the Object Library, select the “UIView”, and drag it into the view.  Next download the swift file from this GitHub link and add it to your project. The moment You add it the Xcode will tell You to create a Swift Bridge. Just create it. Change the Class name of UIView to “SevenSwitch”.Make the Proper IBOutlet connection for this View.
  5. Now import @class SevenSwitch in the ViewController.h . It will Look something like this .

#import <UIKit/UIKit.h>

@class SevenSwitch;

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet SevenSwitch *switchToogle;

6. Now go to ViewController.m  and and import these two files.

7.Now we have to wrie following code in our ViewDidLoad and we have to define one button for the SwitchButton Action. take two image in Your Project to show the images as on and off

#import “ViewController.h”

#import “CustomizeSwitch-Bridging-Header.h”

#import “CustomizeSwitch-Swift.h”

 

@interface ViewController ()

 

@end

@implementation ViewController

– (void)viewDidLoad {

[super viewDidLoad];

[self.switchToogle addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];

self.switchToogle .offImage = [UIImage imageNamed:@”bike.png”];

self.switchToogle .onImage = [UIImage imageNamed:@”office.png”];

self.switchToogle .onTintColor = [UIColor colorWithHue:0.08f saturation:0.74f brightness:1.00f alpha:1.00f];

self.switchToogle .isRounded = NO;

[self.switchToogle setOn:YES animated:YES];

// Do any additional setup after loading the view, typically from a nib.

}

– (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

– (void)switchChanged:(SevenSwitch *)sender {

NSLog(@”Changed value to: %@”, sender.on ? @”ON” : @”OFF”);

}

@end

8. Now Run the project and see the desired output. Enjoy coding. 🙂

Advertisements