Search code examples
iosuiswitch

How to set multiple UISwitches ON which are created in loop programmatically in iOS?


I have done following code for creating multiple UISwitches programmatically and handle particular switch.

for (int i =0; i < 3; i++) {

    CGRect frame = CGRectMake(x, y, height, width);
    UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];

    //add tag as index 
    switchControl.tag = i;
    [switchControl addTarget:self action:@selector(flip:) forControlEvents: UIControlEventValueChanged];

    [switchControl setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:switchControl];

    y= y+50.0;
}

- (IBAction) flip: (id) sender {
    UISwitch *onoff = (UISwitch *) sender;
    NSLog(@"no.%d %@",onoff.tag, onoff.on ? @"On" : @"Off");
    //use onoff.tag , you know which switch you got 
}

After doing this code I want set all UISwitches ON when UIButton select all clicked. How?


Solution

  • To set them all ON I'd save them in an array for easier access. Then you could do:

    for (int i = 0; i < [switchArray count]; i++) {
      UISwitch *sw = (UISwitch *)[switchArray objectAtIndex:i];
      [sw setOn:YES];
    }
    

    You can also do it like that:

    for (int i = 0; i < 3; i++) {
      UISwitch *sw = (UISwitch *)[self.view viewWithTag:i];
      [sw setOn:YES];
    }
    

    Just make sure that tags are unique.

    Hope it helps.