【问题标题】:How to create UISwitch in for loop in iphone?如何在 iPhone 的 for 循环中创建 UISwitch?
【发布时间】:2012-05-16 07:20:20
【问题描述】:

我在 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。现在我不知道如何处理每个开关上的动作。如果有人知道如何处理所有开关上的操作,请帮助我。我会感激他/她。提前致谢。

【问题讨论】:

    标签: iphone uiswitch


    【解决方案1】:
    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 
    }
    

    【讨论】:

    • 它的开关,您将更改事件更改为值更改而不是内部修饰
    • 我在通过单击一个按钮将它们全部打开时遇到问题。如果您知道我该怎么做,请帮助我。
    【解决方案2】:

    是 UIControlEventValueChanged 事件

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

    【讨论】:

    • 你疯了。这是谁做的。如果你不知道怎么做就离开编程
    猜你喜欢
    • 1970-01-01
    • 2021-11-27
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多