随机 IBAction,每个案例仅选择一次
我在制作 IBAction 时遇到问题,该 IBAction 以随机顺序调用每个案例一次。
我做了很多搜索,但没有找到解决这个问题的好的解决方案。 到目前为止我拥有的代码
-(IBAction) random {
int text = rand() % 5;
switch (text) {
case 0:
textview.text = @"1";
break;
case 1:
textview.text = @"2";
break;
case 2:
textview.text = @"3";
break;
case 3:
textview.text = @"4";
break;
case 4:
textview.text = @"5";
break;
default:
break;
}
}
工作正常,但就像我说的,我只希望它调用每个案例一次。
任何帮助将不胜感激。
I am having a problem making a IBAction that calls each case once in a random order.
I have done a lot of searching and not find a good solution to go about this problem.
The code I have so far is
-(IBAction) random {
int text = rand() % 5;
switch (text) {
case 0:
textview.text = @"1";
break;
case 1:
textview.text = @"2";
break;
case 2:
textview.text = @"3";
break;
case 3:
textview.text = @"4";
break;
case 4:
textview.text = @"5";
break;
default:
break;
}
}
It works fine, but like I said, I only want it to call each case once.
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您正在尝试设置随机文本,因此我会这样做:
添加一个名为 stringsArray 之类的 iVar 并在 init 上初始化它:
您的 IBAction 将如下所示:
Since you are trying to set a random text, I'd do it like this:
Add an iVar called something like stringsArray and initialize it on your init:
Your IBAction would look like this:
将选项(如 NSNumber )放入 NSMutableArray 中,选择一个随机索引,显示它,然后将其从数组中删除......如果有其他一些响应,怎么样?计数达到零。
What about putting the options, as
NSNumber
s, in anNSMutableArray
, selecting a random index, display it, and remove it from the array...with some other response if the count reaches zero.使用 srand 代替 rand 函数
或者最好还是使用
int text = arc4random() % 5;
Use srand instead of rand function
Or Better still use
int text = arc4random() % 5;
好吧,不管怎样,您需要保留一张“记分卡”并跳过已经选择的选项。记分卡可以是位图(例如,设置位的简单整数)、布尔数组、先前选择的数字列表等。
最直接的编码方法是拥有逻辑主体上面的 UNTIL 循环中,在选择随机数后检查循环,看看它是否已经被选择。如果是这样,则在循环中进行迭代,否则设置您的响应,在记分卡中填写适当的“复选标记”,然后离开循环。
但要注意:循环还必须包括检查是否已选择所有选项,并在这种情况下退出并带有一些适当的指示。
Well, one way or another you need to keep a "scorecard" and skip options that have already been selected. The scorecard can be a bit map (eg, a simple integer where you set bits), an array of booleans, a list of previously chosen numbers, etc.
The most straight-forward way to code it is to have the body of your logic above in an UNTIL loop and check in the loop, after picking the random number, to see if it's already chosen. If so, iterate in the loop, otherwise set your response, fill in the appropriate "checkmark" in your scorecard, and LEAVE the loop.
But BEWARE: The loop must also include a check to see if all options have already been chosen, and exit with some appropriate indication in that case.