我有这种方法,它会在它们旁边显示UILabels和UISwitches。我希望通过按下标签来打开和关闭UISwitch。我已经标记了开关,但我不知道下一步该怎么做..任何帮助都会非常感激。谢谢!
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];
}
答案 0 :(得分:1)
使用UIButton
代替UILabel
并在其上设置IBAction
。您可以将按钮设置为与标签完全相同的样式。您的IBAction
方法应该如下所示:
- (void)buttonPressed:(UIButton *)sender
{
//Get the view by tag
UISwitch *mySwitch = (UISwitch *)[self.view viewWithTag:yourTag];
[mySwitch.setOn:![mySwitch isOn]];
}
修改强>
如上所述,由于您在代码中构建UIButton
,因此您需要将目标添加到按钮以获取按钮单击。按原样添加操作:
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
答案 1 :(得分:0)
为每个标签添加点按手势识别器。点击它时,您可以从手势(view
)获取标签。现在你只需要让开关更新。
您可以在标签1000 + i
上添加标签,然后通过简单的减法为您提供需要查找的开关标记。
您可以标记标签并将标记用作数组或开关的索引(可能是IBOutletCollection
)。
答案 2 :(得分:0)
你可以这样做。
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];
}