首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在iphone中创建UISwitch in for循环?

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

Stack Overflow用户
提问于 2012-05-16 15:20:20
回答 2查看 495关注 0票数 3

我已经做了以下代码在视图加载创建多个开关编程。

代码语言:javascript
复制
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");
}

完成这段代码后,我可以创建多个UISwitchs。现在我不知道如何处理每个开关上的操作。如果有人知道如何处理所有开关上的动作,请帮助我。我会感谢他/她。提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-16 15:21:47

代码语言:javascript
复制
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 
}
票数 3
EN

Stack Overflow用户

发布于 2012-05-16 15:21:51

它是UIControlEventValueChanged事件

代码语言:javascript
复制
[switchControl addTarget:self action:@selector(flip:) forControlEvents:UIControlEventValueChanged];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10613768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档