设置按钮标题&来自Mutable Array或Dictionary的动作?

时间:2011-12-07 13:39:14

标签: ios button dictionary nsstring nsmutablearray

我有4个可能的答案:3个不正确,1个正确。

我将4个答案存储在“choiceValue”可变数组中作为NSStrings。

    [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];

理想情况下,由于我在“行动”上调用了不同的方法,这取决于答案是正确还是不正确,我相信使用字典(一对“标题”/“方法名称”)会更好。 但是现在如果我可以使用可变数组 - 它会很棒。

非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

正确的输入是指针,不用担心。我能够使用以下代码显示一个按钮,并根据您的示例进行调整。

NSMutableArray* choiceValue = [NSMutableArray new];
[choiceValue addObject:[NSString stringWithFormat:@"%d", 42]];
[button1 setTitle:[choiceValue objectAtIndex:0] forState:UIControlStateNormal]; // Assumes button1 is already instantiated and visible

您确定数组中的字符串是否正确创建?您正在使用%d来指定它们,这使我相信它们是整数。你可以验证这个并用类似的字符串调用注销吗?你可以使用硬编码的字符串作为按钮标题吗?

NSLog([NSString stringWithFormat:@"%d", incorrectOne]); // Test that your string is created correctly
[button1 setTitle:@"42" forState:UIControlStateNormal]; // Test that your button is capable of displaying a title
相关问题