Search code examples
iphoneuiswitch

How to create UISwitch in for loop in iphone?


I have done following code in Viewdid Load for creating multiple switch programmatically.

float x =40.0, y=20.0,height=60.0,width=26.0;

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

        CGRect frame = CGRectMake(x, y, height, width);
        UISwitch *switchControl = [[UISwitch alloc] initWithFrame:frame];
        [switchControl addTarget:self action:@selector(flip:) forControlEvents:UIControlEventTouchUpInside];

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

        y= y+50.0;
    }

- (IBAction) flip: (id) sender {
    UISwitch *onoff = (UISwitch *) sender;
    NSLog(@"%@", onoff.on ? @"On" : @"Off");
}

After doing this code i am able to create multiple UISwitchs. Now i am not getting how to handle action on every switch. If anyone knows how to handle actions on all switchs please help me. I will appreciate to him/her. Thanks in advance.


Solution

  • 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 
    }