如何在iphone中创建for循环中的UISwitch?

时间:2012-05-16 07:20:20

标签: iphone uiswitch

我在Viewdid Load中完成了以下代码,用于以编程方式创建多个切换。

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");
}

执行此代码后,我可以创建多个UISwitch。现在我没有得到如何处理每个开关上的动作。如果有人知道如何处理所有开关上的操作,请帮助我。我会感激他/她。提前谢谢。

2 个答案:

答案 0 :(得分:3)

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 
}

答案 1 :(得分:0)

是UIControlEventValueChanged事件

[switchControl addTarget:self action:@selector(flip:) forControlEvents:UIControlEventValueChanged];