【问题标题】:Set button title & action from Mutable Array or Dictionary?从可变数组或字典设置按钮标题和操作?
【发布时间】: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


【解决方案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

【讨论】:

  • 这回答了我的问题。谢谢@SomeRandomGuy!我做错的是,当我以不同的方法“启动”时,我的阵列从未启动过。您的顶级代码解决了问题。
  • 很高兴能帮上忙!如果您认为我的回答直接导致您解决了问题,请通过单击我的回答左侧的复选框将其标记为“已接受的答案”。它结束了您的问题,并鼓励更多人在未来回答您的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 1970-01-01
  • 2020-11-23
  • 2016-12-17
相关资源
最近更新 更多