首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按下UISwitch UILabel,打开/关闭UILabel

按下UISwitch UILabel,打开/关闭UILabel
EN

Stack Overflow用户
提问于 2014-02-28 15:46:55
回答 3查看 1.2K关注 0票数 0

如果它显示UILabels和UISwitches就在它们旁边,我就得到了这个方法。我希望通过在标签上按下来打开和关闭UISwitch。我已经给开关贴上了标签,但我不知道下一步该怎么做。任何帮助都会很感激。谢谢!

代码语言:javascript
复制
while (i < numberOfAnswers) {
    UILabel *answerLabel = [[UILabel alloc] initWithFrame:CGRectMake(65, y+spaceBetweenAnswers, 240, 30)];
    answerLabel.text = [NSString stringWithFormat:@"%@ (%@)", questionBank[randomQuestionNumber][1][i][0],questionBank[randomQuestionNumber][1][i][1]];
    answerLabel.font = [UIFont systemFontOfSize:15];
    answerLabel.textColor = [UIColor darkGrayColor];
    answerLabel.numberOfLines=0;
    [answerLabel sizeToFit];
    [_answerView addSubview:answerLabel];
    answerHeight = answerLabel.frame.size.height + spaceBetweenAnswers;

    UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(10, y+spaceBetweenAnswers-5, 0, 30)];
    mySwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);
    if ([questionBank[randomQuestionNumber][1][i][1] isEqual:@"0"]) {
         [mySwitch addTarget:self action:@selector(wrongAnswer:) forControlEvents:UIControlEventValueChanged];
    } else {
    }
    mySwitch.tag = i;
    [_answerView addSubview:mySwitch];
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-02-28 16:06:49

使用UIButton而不是UILabel,并在其上设置IBAction。您可以将按钮的样式设计成与标签完全相同的样式。您的IBAction方法应该如下所示:

代码语言:javascript
复制
- (void)buttonPressed:(UIButton *)sender
{
    //Get the view by tag
    UISwitch *mySwitch = (UISwitch *)[self.view viewWithTag:yourTag];
    [mySwitch.setOn:![mySwitch isOn]];
}

编辑

如前所述,由于您是在代码中构建UIButton,因此需要将目标添加到按钮中,以使按钮单击。添加这样的操作:

代码语言:javascript
复制
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
票数 1
EN

Stack Overflow用户

发布于 2014-02-28 15:53:28

在每个标签上添加一个点击手势识别器。当它被点击时,您可以从手势(view)中获得标签。现在你只需要让开关更新。

您可以在标签中添加一个标签,即1000 + i,然后简单的减法就会给出您需要找到的开关标记。

您可以标记标签,并将标记用作数组或开关(可能是IBOutletCollection)中的索引。

票数 0
EN

Stack Overflow用户

发布于 2014-02-28 18:29:26

你可以做这样的事。

代码语言:javascript
复制
UISwitch* mySwitch = [[UISwitch alloc]init];
[self addSubview:mySwitch];

UIButton* switchLabelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
switchLabelBtn.frame = CGRectMake(0, 0, 80, 40);
[switchLabelBtn addTarget:self action:@selector(switchLabelbtnTapped:) forControlEvents:UIControlEventTouchUpInside];
[switchLabelBtn.layer setValue:mySwitch forKey:@"Switch"];
[self addSubview:switchLabelBtn];


- (void)switchLabelbtnTapped:(UIButton*)sender
{
    UISwitch* mySwitch = [sender.layer valueForKey:@"Switch"];
    mySwitch.on = ![mySwitch isOn];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22099614

复制
相关文章

相似问题

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