【问题标题】:How to set multiple UISwitches ON which are created in loop programmatically in iOS?如何在 iOS 中以编程方式将多个 UISwitches 设置为 ON?
【发布时间】:2012-05-21 11:17:55
【问题描述】:

我已经完成了以下代码,用于以编程方式创建多个 UISwitches 并处理特定的开关。

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 
}

完成此代码后,我想在 UIButton 选择所有单击时将所有 UISwitches 设置为 ON。怎么样?

【问题讨论】:

    标签: ios uiswitch


    【解决方案1】:

    要将它们全部设置ON 我会将它们保存在一个数组中以便于访问。然后你可以这样做:

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

    你也可以这样做:

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

    只要确保标签是唯一的。

    希望对你有帮助。

    【讨论】:

    • 请告诉我如何在这里制作 switchArray。我试过了,但它给出的错误表达式不可分配。我是 iPhone 的新手。所以我的问题可能很简单。
    • @python 在for-loop 之前声明一个数组。然后在循环中将该开关添加到数组中。我会为此使用NSMutableArray。在标题中:NSMutableArray *switchArray;,然后在 for 循环之前的实现文件中:switchArray = [NSMutableArray array]; 和循环结束(但仍在循环中):[switchArray addObject:switchControl];。希望对你有帮助
    • 对此我还有一个疑问。我如何在其他方法中检查开关位置。它需要 IBOutlet。我如何在循环中务实地创建 IBOutlet?如果你知道请帮助我。
    • @python 检查它是ON 还是OFF 使用isOn 方法UISwitch。示例:if ([sw isOn]) { //doSmth} else {//doSmthElse}
    【解决方案2】:

    在那里使用这个东西 请以 100 或 1000 开头的标签号

    -(void) selectAll {
    for(int i=100;i<(100+3);i++){
    UISwitch *refSwitch=[self.view viewWithTag:i];
    refSwitch.on=YES;
    }
    }
    

    这对你有用

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 2011-12-09
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 2020-06-10
      相关资源
      最近更新 更多