【发布时间】:2011-12-07 13:39:13
【问题描述】:
我有 4 个可能的答案:3 个不正确,1 个正确。
我将 4 答案作为 NSStrings 存储在“choiceValue”可变数组中。
[choiceValue addObject:[NSString stringWithFormat:@"%d", incorrectOne]];
[choiceValue addObject:[NSString stringWithFormat:@"%d", incorrectTwo]];
[choiceValue addObject:[NSString stringWithFormat:@"%d", incorrectThree]];
[choiceValue addObject:[NSString stringWithFormat:@"%d", correctAnswer]];
然后我将打乱数组顺序(不是这个问题主题的一部分)
我想根据(洗牌的)数组索引来分配 4 个按钮的标题(setTitle)。
我尝试了以下代码,但我相信我遗漏了一些东西:
[button1 setTitle:[choiceValue objectAtIndex:0] forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(handleIncorrectAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:[choiceValue objectAtIndex:3] forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(handleCorrectAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button3 setTitle:[choiceValue objectAtIndex:1] forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(handleIncorrectAnswer:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:[choiceValue objectAtIndex:2] forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(handleIncorrectAnswer:) forControlEvents:UIControlEventTouchUpInside];
理想情况下,由于我根据答案的正确或错误在“操作”上调用不同的方法,我相信最好使用字典(一对“标题”/“方法名称”)来完成。 但是现在,如果我可以让它与可变数组一起使用 - 那就太好了。
非常感谢您的帮助!
【问题讨论】:
-
我推荐一种不同的方法:在单独的变量中维护正确选项的索引。对所有按钮使用相同的目标。在被调用的方法中确定按下了哪个按钮(使用标签或 IBOutletCollection 并采取相应的措施。
-
当你运行这个时,什么地方看起来不正确?
-
@SanjayChaudhry 首先我尝试使用相同的目标,但决定使用该线程的建议,因为它看起来更好:stackoverflow.com/questions/8368242/…
-
@SomeRandomGuy - 问题是按钮不显示任何内容。我相信这是因为我返回的是指向 NSString 而不是字符串本身的指针。有什么想法吗?
标签: ios button dictionary nsstring nsmutablearray