3

プログラムで複数のスイッチを作成するために、ViewdidLoadで次のコードを実行しました。

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を作成できます。今、私はすべてのスイッチでアクションを処理する方法を取得していません。誰かがすべてのスイッチでアクションを処理する方法を知っているなら、私を助けてください。彼/彼女に感謝します。前もって感謝します。

4

2 に答える 2

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 
}
于 2012-05-16T07:21:47.323 に答える
0

UIControlEventValueChanged イベントです

[switchControl addTarget:self action:@selector(flip:) forControlEvents:UIControlEventValueChanged];
于 2012-05-16T07:21:51.003 に答える