问题描述
我创建了一个测验,将问题从plist抽取到数组中,并在uilabel中显示问题,并在uibuttons中显示三个可能的答案.我的问题是如何为按钮创建随机顺序,以使三个答案不总是按相同顺序显示?
I have created a quiz which draws questions from a plist into an array and displays the question in a uilabel and the three possible answers in uibuttons. My question is how can I create a random order for the buttons so that the three answers don't always show up in the same order?
任何帮助将不胜感激.
杰米
推荐答案
与@Abizern的答案一起使用.具有固定的按钮并使数组随机化会更有效.您可以执行以下操作:
Going along with @Abizern's answer. It would be more efficient to have the fixed buttons and randomise the array. You could do something like this:
//NSMutableArray *questions = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", @"4", nil];
NSMutableArray *unorderedQuestions = [[NSMutableArray alloc] init];
for (int i=0; i < [questions count]; i++) {
int lowerBound = 0;
int upperBound = 100;
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
[unorderedQuestions addObject:[[NSArray alloc] initWithObjects:[questions objectAtIndex:i], [NSString stringWithFormat:@"%i", rndValue], nil]];
}
NSArray* sortedArray = [unorderedQuestions sortedArrayUsingFunction:order context:NULL];
//or
// questions = [unorderedQuestions sortedArrayUsingFunction:order context:NULL];
NSLog(@"%@", sortedArray);
并将此函数放在某处:
static NSInteger order (id a, id b, void* context) {
NSString* catA = [a lastObject];
NSString* catB = [b lastObject];
return [catA caseInsensitiveCompare:catB];
}
这基本上为每个问题分配一个随机数(0到100之间),并按该数字对其进行排序.然后,您可以将sortedArray
设置为全局(或者可能只是覆盖您的questions
数组)并顺序显示对象,它们将被重新排列.
This basically assigns a random number (between 0 and 100) to each question and sorts it by that number. You can then just make sortedArray
global (or possibly just overwrite your questions
array) and display objects sequentially and they will be shuffled.
[btnA setTitle:[[[questions objectAtIndex:r] objectAtIndex:0] objectForKey:@"A"] forState:UIControlStateNormal];
根据您的代码判断,您可能需要修改几行:(但您也可以在上面的代码之前创建一个currentQuestionsArray
并将其分配给[questions objectAtIndex:r]
)
Judging by your code, you may need to amend a few lines: (but you could also create a currentQuestionsArray
and assign it to [questions objectAtIndex:r]
before the code above)
for (int i=0; i < [questions count]; i++) {
//to
for (int i=0; i < [[questions objectAtIndex:r] count]; i++) {`
和
[unorderedQuestions addObject:[[NSArray alloc] initWithObjects:[questions objectAtIndex:i], [NSString stringWithFormat:@"%i", rndValue], nil]];
//to
[unorderedQuestions addObject:[[NSArray alloc] initWithObjects:[[questions objectAtIndex:r] objectAtIndex:i], [NSString stringWithFormat:@"%i", rndValue], nil]];`
我认为这是最可靠的解决方案,因为将来您针对特定问题可能会有不同数量的答案,因此无需进行编辑即可!
I think this is the most robust solution, as in the future you may have a different number of answers for a particular question and would not need to edit this to do so!
这篇关于按钮的随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!