如果它显示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];
}发布于 2014-02-28 16:06:49
使用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];发布于 2014-02-28 15:53:28
在每个标签上添加一个点击手势识别器。当它被点击时,您可以从手势(view)中获得标签。现在你只需要让开关更新。
您可以在标签中添加一个标签,即1000 + i,然后简单的减法就会给出您需要找到的开关标记。
您可以标记标签,并将标记用作数组或开关(可能是IBOutletCollection)中的索引。
发布于 2014-02-28 18:29:26
你可以做这样的事。
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];
}https://stackoverflow.com/questions/22099614
复制相似问题