我有一个问题视图,将显示4个答案,只有1个正确。

但是我不希望同一个按钮总是正确的答案。

我想知道我如何每次随机放置4个UIButton和值。



当用户再次转到该问题时,答案将在不同的按钮中



我的X,y,W,H位置

按钮1
5,219,230,45

按钮2
5,273,230,45

按钮3
244,224,230,45

按钮4
244,273,230,45

最佳答案

我碰巧正在开发类似的游戏应用程序,因此获得了一些肯定会有所帮助的代码。在下面查看。请注意,我把它称为正确和不正确按钮单击的“ correctAnswerMethod”和“ wrongAnswerMethod”。

// Define the four buttons in their respective frames, create the first button as the correct one, we'll shuffle it later.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"Correct Answer" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(correctAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button1];

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button2 setTitle:@"Wrong Answer 1" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button2];

UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button3 setTitle:@"Wrong Answer 2" forState:UIControlStateNormal];
[button3 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button3];

UIButton *button4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button4 setTitle:@"Wrong Answer 3" forState:UIControlStateNormal];
[button4 addTarget:self action:@selector(wrongAnswerMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button4];


//Create an array with the rectangles used for the frames
NSMutableArray *indexArray = [NSMutableArray arrayWithObjects:
                              [NSValue valueWithCGRect:CGRectMake(5, 219, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(5, 273, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(244, 219, 230, 45)],
                              [NSValue valueWithCGRect:CGRectMake(244, 273, 230, 45)], nil];

//Randomize the array
NSUInteger count = [indexArray count];
for (NSUInteger i = 0; i < count; ++i) {
    int nElements = count - i;
    int n = (arc4random() % nElements) + i;
    [indexArray exchangeObjectAtIndex:i withObjectAtIndex:n];
}

//Assign the frames
button1.frame = [((NSValue *)[indexArray objectAtIndex:0]) CGRectValue];
button2.frame = [((NSValue *)[indexArray objectAtIndex:1]) CGRectValue];
button3.frame = [((NSValue *)[indexArray objectAtIndex:2]) CGRectValue];
button4.frame = [((NSValue *)[indexArray objectAtIndex:3]) CGRectValue];

关于iphone - 如何随机放置UIButton和值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9714559/

10-13 04:10