iOS - Switches



Use of Switches

Switches are used to toggle between on and off states.

Important Properties

  • onImage
  • offImage
  • on

Important Method

- (void)setOn:(BOOL)on animated:(BOOL)animated

Add Custom Methods addSwitch and switched

-(IBAction)switched:(id)sender {
   NSLog(@"Switch current state %@", mySwitch.on ? @"On" : @"Off");
}

-(void)addSwitch {
   mySwitch = [[UISwitch alloc] init];
   [self.view addSubview:mySwitch];
   mySwitch.center = CGPointMake(150, 200);
   [mySwitch addTarget:self action:@selector(switched:)
   forControlEvents:UIControlEventValueChanged];
}

Update viewDidLoad in ViewController.m as follows −

(void)viewDidLoad {
   [super viewDidLoad];
   [self addSwitch];
}

Output

When we run the application, we'll get the following output −

iOS Tutorial

On swiping the switch to the right, the output is as follows −

iOS Tutorial
ios_ui_elements.htm
Advertisements